Is it possible to reference an outer query from an inner query in the context of a join? The "where (sid.ItemID = i.itemID)" of the inner query is giving me an error. I thought I did this in the past so I search through all my stored procs but apparently I did some kind of substitution to get it to work. I suspect I can delete that line and it will work but is it more effecient with that inner where clause?
SELECT departmentName
, supplierName
, so.SalesOrderID
, ss.warehouseInvoiceNo
, ss.transactionNo
, ss.storeID
, s.storeName
, s.storeNo
, tr.transactionDate
, p.period
, sooos.salesOrderID
, sooos.salesOrderOutOfStockID
, sooos.itemID
, i.itemNo
, i.itemName
, i.pack
, i.unitSize
, quantity
, wi.available
FROM SalesOrderOutOfStock sooos
JOIN Item AS i ON i.ItemID = sooos.ItemID
JOIN SalesOrder so ON so.SalesOrderID = sooos.SalesOrderID
JOIN WarehouseInventory wi ON wi.ItemID = sooos.ItemID
JOIN Store s ON s.StoreID = so.StoreID
JOIN InvoiceOrderRelationship ior ON ior.SalesOrderID = so.SalesOrderID
JOIN StockSale ss ON ss.WarehouseInvoiceNo = ior.WarehouseInvoiceNo
JOIN TransactionRegister tr ON tr.TransactionNo = ss.TransactionNo
JOIN Period p ON p.PeriodID = tr.PeriodID
JOIN Department d ON d.DepartmentID = i.DepartmentID
LEFT OUTER JOIN (SELECT TOP 1 itemID
, supplierID
FROM SupplierInvoiceDetail sid
JOIN SupplierInvoice si ON si.SupplierInvoiceID = sid.SupplierInvoiceID
--where (sid.ItemID = i.itemID)
order by InvoiceDate desc
--NEED AN ORDER BY HERE
) AS lastSupplier ON lastSupplier.ItemID = i.ItemID
JOIN supplier su ON su.SupplierID = Isnull(lastSupplier.supplierID, i.supplierID)
WHERE ss.WarehouseInvoiceNo = 10000000
--$P{invoiceNo}
You need to use OUTER APPLY here rather than LEFT JOIN:
OUTER APPLY (SELECT TOP 1 itemID
, supplierID
FROM SupplierInvoiceDetail sid
JOIN SupplierInvoice si ON si.SupplierInvoiceID = sid.SupplierInvoiceID
where (sid.ItemID = i.itemID) order by InvoiceDate desc
) AS lastSupplier
Subqueries introduced in FROM or JOIN clauses cannot refer to other table sources within the same FROM clause (effectively, they should all be evaluatable simultaneously). APPLY allows you to introduce a specific dependency in the evaluation.
Related
The original question and schema are shown at the following link:
SQL query to retrieve the latest status of a process
The solution provided by #mendosi was perfect. However, now that the deadline for submission is past, management wants more information. I've been able to give them the information they want using the following query (incorporating the aforementioned solution into the "EXISTS" clause):
SELECT
proposalPackage.proposalPackageID, refProposalType.name, proposalPackage.title,
[user].lastName, [user].firstName, [user].email, [user].phone,
proposalReviewAction.approvalTypeID
FROM
proposalReviewAction, proposalPackage
INNER JOIN
refProposalType ON proposalPackage.proposalTypeID = refProposalType.proposalTypeID
INNER JOIN
proposalManagerAssignment ON proposalPackage.proposalPackageID = proposalManagerAssignment.proposalPackageID
INNER JOIN
[user] ON proposalManagerAssignment.userID = [user].userID
WHERE
EXISTS (SELECT ls.*
FROM
(SELECT
r.proposalPackageID, r.approvalTypeID,
RowNr = ROW_NUMBER() OVER (PARTITION BY r.proposalPackageID ORDER BY r.reviewedDate DESC)
FROM
proposalReviewAction AS r
JOIN
proposalPackage AS pp ON pp.proposalPackageID = r.proposalPackageID
WHERE
pp.proposalCallID = 7) AS ls
WHERE
ls.RowNr = 1
AND (ls.approvalTypeID = 50))
GROUP BY
proposalPackage.proposalTypeID, [user].lastName, [user].firstName,
[user].email, [user].phone, proposalPackage.title,
refProposalType.name, proposalManagerAssignment.isPrimary,
proposalPackage.proposalCallID, approvalTypeID,
proposalPackage.proposalPackageID, proposalReviewAction.approvalTypeID
HAVING
(proposalManagerAssignment.isPrimary = 1)
AND (proposalPackage.proposalCallID = 7)
AND (approvalTypeID = 50)
ORDER BY
proposalPackage.proposalPackageID
My problem seems to be that the subquery in the Exists clause returns 95 rows (as it should) limiting the results to those with a status of 50.
As I understand the EXISTS clause, the results should be limited to those records that "exist" in the subquery that follows... right? So, in this case, if a record does not exist in the subquery, it will not exist in the final result...??
The problem is, I'm getting 112 records when there are only 95 records to choose from (or join on) in the results list of the subquery.
So, I try to limit is by adding some additional qualifiers and joins to the subquery:
SELECT
proposalPackage.proposalPackageID, refProposalType.name,
proposalPackage.title,
[user].lastName, [user].firstName, [user].email, [user].phone,
proposalReviewAction.approvalTypeID
FROM
proposalReviewAction, proposalPackage
INNER JOIN
refProposalType ON proposalPackage.proposalTypeID = refProposalType.proposalTypeID
INNER JOIN
proposalManagerAssignment ON proposalPackage.proposalPackageID = proposalManagerAssignment.proposalPackageID
INNER JOIN
[user] ON proposalManagerAssignment.userID = [user].userID
WHERE
EXISTS (SELECT ls.*
FROM
(SELECT
r.proposalPackageID,
r.approvalTypeID,
RowNr = ROW_NUMBER() OVER (PARTITION BY r.proposalPackageID ORDER BY r.reviewedDate DESC)
FROM
proposalReviewAction AS r
JOIN
proposalPackage AS pp ON pp.proposalPackageID = r.proposalPackageID
WHERE
pp.proposalCallID = 7) AS ls
WHERE
ls.RowNr = 1
AND (ls.approvalTypeID = 50)) AS distinctified
INNER JOIN
proposalPackage ON distinctified.proposalPackageID = proposalPackage.proposalPackageID
INNER JOIN
refProposalApprovalType ON distinctified.approvalTypeID = refProposalApprovalType.approvalTypeID
GROUP BY
proposalPackage.proposalTypeID, [user].lastName, [user].firstName,
[user].email, [user].phone, proposalPackage.title, refProposalType.name,
proposalManagerAssignment.isPrimary, proposalPackage.proposalCallID,
approvalTypeID, proposalPackage.proposalPackageID, proposalReviewAction.approvalTypeID
HAVING
(proposalManagerAssignment.isPrimary = 1)
AND (proposalPackage.proposalCallID = 7)
AND (distinctified.approvalTypeID = 50)
ORDER BY
proposalPackage.proposalPackageID
Now, when I add the "AS distinctified" statement with a couple of JOINS to the subquery, I get a "SYNTAX ERROR near AS" error. I also get an "Expecting ( or SELECT" at each of the "HAVING" qualifiers.
I don't think I'm making this too complicated but that remains a possibility. It seems to me it is a matter (at this point) of overlooking a character somewhere.
Thanks in advance for the assist... AGAIN!!
This isn't really an answer to your much more complex example, but it should explain what the root cause is hopefully?
DECLARE #x TABLE (id INT);
INSERT INTO #x SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3;
DECLARE #y TABLE (id INT);
INSERT INTO #y SELECT 1 UNION ALL SELECT 3;
--This is what you are doing
SELECT * FROM #x WHERE EXISTS (SELECT * FROM #y);
--This is what you should be doing
SELECT * FROM #x x WHERE EXISTS (SELECT * FROM #y y WHERE y.id = x.id);
I really have no idea what you are trying to accomplish but here is what your query might look like with some aliases and formatting. I also moved the joins before the where clause and removed the alias on your EXISTS predicate. But you are referencing distinctified in the code which I just don't get. As such there are some issues in this query still but without an understanding of what the need is I don't know what to do to help.
SELECT pp.proposalPackageID
, pt.name
, pp.title
, u.lastName
, u.firstName
, u.email
, u.phone
, pra.approvalTypeID
FROM proposalReviewAction pra
--, proposalPackage pp --why is this table here? It is joined to again later
INNER JOIN refProposalType pt ON pp.proposalTypeID = pt.proposalTypeID
INNER JOIN proposalManagerAssignment ma ON pp.proposalPackageID = ma.proposalPackageID
INNER JOIN [user] u ON ma.userID = u.userID
INNER JOIN proposalPackage pp ON distinctified.proposalPackageID = pp.proposalPackageID
INNER JOIN refProposalApprovalType pat ON distinctified.approvalTypeID = pat.approvalTypeID
WHERE EXISTS
(
SELECT ls.*
FROM
(
SELECT r.proposalPackageID,
r.approvalTypeID,
RowNr = ROW_NUMBER() OVER (PARTITION BY r.proposalPackageID ORDER BY r.reviewedDate DESC)
FROM proposalReviewAction AS r
JOIN proposalPackage AS pp2 ON pp2.proposalPackageID = r.proposalPackageID
WHERE pp2.proposalCallID = 7
) AS ls
WHERE ls.RowNr = 1
AND ls.approvalTypeID = 50
)
GROUP BY pp.proposalTypeID
, u.lastName
, u.firstName
, u.email
, u.phone
, pp.title
, pt.name
, ma.isPrimary
, pp.proposalCallID
, approvalTypeID
, pp.proposalPackageID
, pra.approvalTypeID
HAVING ma.isPrimary = 1
AND pp.proposalCallID = 7
AND distinctified.approvalTypeID = 50
ORDER BY pp.proposalPackageID
So, I figured it out... once I realized I had the wrong understanding of EXISTS (thanks #Richard Hansel). Final query: (properly formatted and aliased)
SELECT pp.proposalPackageID
, r_pt.name
, pp.title
, u.lastName
, u.firstName
, u.email
, u.phone
, pra.approvalTypeID
FROM proposalReviewAction AS pra
, proposalPackage AS pp
INNER JOIN refProposalType AS r_pt ON pp.proposalTypeID = r_pt.proposalTypeID
INNER JOIN proposalManagerAssignment AS pma ON pp.proposalPackageID = pma.proposalPackageID
INNER JOIN [user] AS u ON pma.userID = u.userID
WHERE EXISTS
(SELECT ls.*
FROM
(SELECT r.proposalPackageID,
r.approvalTypeID,
RowNr = ROW_NUMBER() OVER (PARTITION BY r.proposalPackageID ORDER BY r.reviewedDate DESC)
FROM proposalReviewAction AS r
JOIN proposalPackage AS pp ON pp.proposalPackageID = r.proposalPackageID
WHERE pp.proposalCallID = 7) AS ls
WHERE ls.RowNr = 1
AND (ls.approvalTypeID = 50)
AND (pra.proposalPackageID = pp.proposalPackageID))
GROUP BY pp.proposalTypeID
, u.lastName
, u.firstName
, u.email
, u.phone
, pp.title
, r_pt.name
, pma.isPrimary
, pp.proposalCallID
, approvalTypeID
, pp.proposalPackageID
, pra.approvalTypeID
HAVING (pma.isPrimary = 1)
AND (pp.proposalCallID = 7)
AND (pra.approvalTypeID = 50)
ORDER BY pp.proposalTypeID
I had written a join query statement. that statement returns me multiple(duplicate) row again even though I'm having only single record on that.
declare #BenefitClass int ;
set #BenefitClass = (select BenefitClass From HJOB where userid='d76c5000-69e0-461e-92e1-3cfe7590d098' and CompanyId =1629)
select #BenefitClass;
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098' and bhsac.PlanInfoId=38044
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId and oems.EndDt > GETDATE()
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
For that I'm getting the result as second row as duplicate :
observe the result
Try this once it may help you
declare #BenefitClass int ;
set #BenefitClass = (select BenefitClass From HJOB where userid='d76c5000-69e0-461e-92e1-3cfe7590d098' and CompanyId =1629)
select #BenefitClass;
;with cte as (
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098' and bhsac.PlanInfoId=38044
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId and oems.EndDt > GETDATE()
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
)
select distinct EmployerContribution,
CatchUpValue ,Tier,planYear,Ischecked,EmployeeContribute,Id ,Value ,HSALmitId from cte
Please change your where condition as below:
select
bve.EmployerContribution,
bhsac.CatchUpValue as CatchUpValue ,
bcl.Tier,
bcl.planYear,
bhsac.Ischecked,
isnull(bhsac.Value,0) as EmployeeContribute,
Id=(convert(varchar, bcl.Id) + '$' + convert(varchar, isnull(bhsac.Id, 0))) ,
bhsac.Value ,
bhsac.HSALmitId
from
dbo.benContributionStructure bcs
inner join dbo.benVariableElection bve on bcs.PlanInfoId = bve.PlanInfoId
inner join dbo.benBenefitContributionLimit bcl on bcs.SavingCategory = bcl.CategoryID
left outer join dbo.benBenefitHSACoverage bhsac on bcs.PlanInfoId = bhsac.planInfoId
and bcl.Id=bhsac.HSALmitId --and bhsac.BenefitClassId=#BenefitClass
left outer join dbo.benEmployeeContribution bec on bhsac.UserID = bec.UserId and bhsac.BenefitClassId = bec.BenefitClassId -- and bec.EnrollmentType !='Closed'
left outer join benOpenEnrollment oems on oems.ID = bec.OpenEnrollmentId
where
bcs.PlanInfoId=38044 and bcl.Ischecked=1
and bcl.Tier !='CatchUp'
and bcl.CompanyId=1629
and bhsac.UserID='d76c5000-69e0-461e-92e1-3cfe7590d098'
and bhsac.PlanInfoId=38044
and oems.EndDt > GETDATE()
I'm trying to display the data so that only one line is displayed per customer, i'm having trouble with trying to achieve that with my code as its returning all records, can anyone help
SELECT customerOrdrs.NAME AS 'Name',
customerOrdrs.currentbalance -
Sum(COALESCE(customerOrdrs.revisedbalance, 0)) AS 'RevisedBalance',
sold AS 'NumberOfItemsSold'
FROM customers,
(SELECT c.NAME AS NAME,
c.balance AS CurrentBalance,
i.qty AS RevisedBalance,
( Min(s.price) * i.qty ) AS Sold
FROM customers c
INNER JOIN sales o
ON c.NAME = o.custname
INNER JOIN purchases i
ON i.orderno = o.orderno
INNER JOIN contracters s
ON i.item = s.item
GROUP BY c.NAME,
c.balance,
i.qty) customerOrdrs
GROUP BY customerOrdrs.NAME,
customerOrdrs.currentbalance,
sold
I'm not sure how your data looks but I have reformatted the query and there are a few things I've noticed off the bat.
I have removed the subquery as I don't believe it is necessary - in addition your original query is referring to customer table twice without defining a join
Select [C].[Name] As [Name]
, [CurrentBalance] = [C].[Balance]
, [RevisedBalance] = [C].[Balance] - Sum([P].[Qty])
, [Sold] = ( Min([CO].[Price]) * sum([P].[Qty]) )
From [CUSTOMERS] [C]
Inner Join [Sales] [s]
On [C].[Name] = [s].[custName]
Inner Join [Purchases] [P]
On [P].[OrderNo] = [s].[OrderNo]
Inner Join [Contracters] [CO]
On [P].[Item] = [CO].[Item]
Group By [C].[Name]
, [C].[Balance];
I have this query:
SELECT
t_ticket.ticketID, t_ticket.addedDate, t_ticket.question,
t_ticket.code, t_ticket.priority, t_orgSection.title,
t_actionTicket.addedDateAction, t_actionTicket.title AS Expr1
FROM
t_actionTicket
INNER JOIN
t_ticket ON t_actionTicket.ticketID_FK = t_ticket.ticketID
INNER JOIN
t_orgSection ON t_ticket.orgSectionID_FK = t_orgSection.orgSectionID
WHERE
(t_ticket.userID_FK = #userid) AND (t_ticket.cusDelete = 0)
I want to return just the latest record in t_actionTicket table for each row in t_ticket table.
You can use row_number to pick just the top row for each ticket ID, by ordering by your date and then making row = 1 one of your join criteria. See as follows:
Replace
FROM t_actionTicket INNER JOIN
t_ticket ON t_actionTicket.ticketID_FK = t_ticket.ticketID
with
FROM
(select *
, row_number() over (partition by ticketID_FK order by TicketActionDate desc) as RN
from t_actionTicket ) at
INNER JOIN t_ticket
ON at.ticketID_FK = t_ticket.ticketID and at.RN = 1
I guessed at the name of your date column in ActionTicket, so you will probably need to change that.
You can try this one too, just alternative:
SELECT t_ticket.ticketID, t_ticket.addedDate, t_ticket.question,t_ticket.code, t_ticket.priority, t_orgSection.title,t_actionTicket.addedDateAction, t_actionTicket.title AS Expr1
FROM t_ticket INNER JOIN
(select TOP 1 t_actionTicket.* from t_actionTicket INNER JOIN
t_ticket on t_ticket.ticketID = t_actionTicket.ticketID_FK ORDER BY
t_actionTicket.addedDateAction DESC ) AS t_actionTicket
ON t_actionTicket.ticketID_FK = t_ticket.ticketID
INNER JOIN t_orgSection ON t_ticket.orgSectionID_FK = t_orgSection.orgSectionID
WHERE (t_ticket.userID_FK = #userid) AND (t_ticket.cusDelete = 0)
I assume that addedDateAction uses timestamp when new record is inserted.
I find this solution
SELECT t_ticket.ticketID, t_ticket.addedDate, t_ticket.question,
t_ticket.code, t_ticket.priority, t_actionTicket.addedDateAction,
t_actionTicket.title AS Expr1
FROM t_actionTicket INNER JOIN t_ticket ON
t_actionTicket.ticketID_FK = t_ticket.ticketID INNER JOIN
(SELECT ticketID_FK, MAX(addedDateAction) AS maxDate
FROM t_actionTicket AS t_actionTicket_1
GROUP BY ticketID_FK) AS b ON t_actionTicket.ticketID_FK = b.ticketID_FK AND t_actionTicket.addedDateAction = b.maxDate
WHERE (t_ticket.userID_FK = #userid) AND (t_ticket.cusDelete = 0)
here's my query. when I inner join 2 tables, there's no problem.
SELECT S.* ,
U.Avatar ,
U.Displayname ,
ROW_NUMBER() OVER ( ORDER BY S.Id DESC ) rownum
FROM dbo.Smoothie AS S
INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
WHERE S.IsPublic = 1
AND S.Status = 3
AND S.UserId = 2
then, I added another inner join. now, I got alot duplications.
SELECT S.* ,
U.Avatar ,
U.Displayname,
ROW_NUMBER() OVER ( ORDER BY S.Id DESC ) rownum
FROM dbo.Smoothie AS S
INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
INNER JOIN dbo.Favorite AS F ON U.Id = F.UserId
WHERE S.IsPublic = 1
AND S.Status = 3
AND F.UserId = 2
one solutions is to use distinct. however, I have to comment out row_number, i need that row_number to do paging. is there another way to get rid of duplication?
SELECT DISTINCT S.* ,
U.Avatar ,
U.Displayname
-- ROW_NUMBER() OVER ( ORDER BY S.Id DESC ) rownum
FROM dbo.Smoothie AS S
INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
INNER JOIN dbo.Favorite AS F ON U.Id = F.UserId
WHERE S.IsPublic = 1
AND S.Status = 3
AND F.UserId = 2
Why not use the query you have, without the row_number as a subquery, then add the row number back later:
SELECT *,
ROW_NUMBER() OVER ( ORDER BY subQuery.Id DESC ) rownum
FROM (
SELECT DISTINCT S.* ,
U.Avatar ,
U.Displayname
FROM dbo.Smoothie AS S
INNER JOIN dbo.[User] AS U ON S.UserId = U.Id
INNER JOIN dbo.Favorite AS F ON U.Id = F.UserId
WHERE S.IsPublic = 1
AND S.Status = 3
AND F.UserId = 2
) AS subQuery
Dense_Rank would also do the job with the your otherwise unmodified query.