i have used below sub-query for returning maximum data of each (Document Number) from my query but it returns just one record while i have many records.
SELECT tblTransmittals.[Owner Document Number]
, tblTransmittals.[Int-Tr- NO]
, tbltransmittalNo.[Internal-Tr-Date]
FROM tblTransmittals
INNER JOIN tbltransmittalNo
ON tblTransmittals.[Int-Tr- NO] = tbltransmittalNo.[Int-Tr-NO]
WHERE (((tbltransmittalNo.[Internal-Tr-Date])=
(SELECT Max(A.[Internal-Tr- Date])
FROM (SELECT tblTransmittals.[Owner Document Number]
, tbltransmittalNo. [Internal-Tr-Date]
FROM tblTransmittals
INNER JOIN tbltransmittalNo
ON tblTransmittals.[Int-Tr-NO] = tbltransmittalNo.[Int-Tr-NO]
) AS A
WHERE A.[owner Document Number]=[tblTransmittals].[Owner Document Number])));
i mean if data of query is like below :
Owner Document Number Int-Tr-NO Internal-Tr-Date
doc-0001 tt-0002 10-oct-2016
doc-0001 tt-0003 12-0ct-2017
doc-0005 tt-0100 18-sep-2015
i would like after using subquery it returns:
Owner Document Number Int-Tr-NO Internal-Tr-Date
doc-0001 tt-0003 12-0ct-2017
doc-0005 tt-0100 18-sep-2015
i tried and checked everything but i do not know why does not work?
Not totally clear what you want here and I am assuming this is sql server. Think you want something like this.
select *
from
(
SELECT t.[Owner Document Number]
, t.[Int-Tr- NO]
, tn.[Internal-Tr-Date]
, RowNum = ROW_NUMBER() over (partition by t.[Owner Document Number] order by tbltransmittalNo.[Internal-Tr-Date] desc)
FROM tblTransmittals t
INNER JOIN tbltransmittalNo tn ON t.[Int-Tr- NO] = tn.[Int-Tr-NO]
) x
where x.RowNum = 1
SELECT tblTransmittals.[Owner Document Number], tblTransmittals.[Int-Tr-NO], tbltransmittalNo.[Internal-Tr-Date]
FROM tblTransmittals INNER JOIN tbltransmittalNo ON tblTransmittals.[Int-Tr-NO] = tbltransmittalNo.[Int-Tr-NO]
WHERE (((tbltransmittalNo.[Internal-Tr-Date])=
(SELECT Max([Internal-Tr-Date])
FROM (SELECT T.[Owner Document Number], T.[Int-Tr-NO], TN.[Internal-Tr-Date]
FROM tblTransmittals AS T LEFT JOIN tbltransmittalNo AS TN ON T.[Int-Tr-NO] = TN.[Int-Tr-NO]) AS A
WHERE A.[owner Document Number]=[tblTransmittals].[Owner Document Number])));
Your query is totally incorrect as it only returns one row due to the max() on your sub-query:
(SELECT Max(A.[Internal-Tr- Date])
FROM (SELECT tblTransmittals.[Owner Document Number], tbltransmittalNo. [Internal-Tr-Date]
FROM tblTransmittals INNER JOIN tbltransmittalNo
ON tblTransmittals.[Int-Tr-NO] = tbltransmittalNo.[Int-Tr-NO]) AS A
WHERE A.[owner Document Number]=[tblTransmittals].[Owner Document Number]);
##this query only returns 1 value
In your scenario above, the max() query will return "12-0ct-2017" and your final query will look like this:
SELECT tblTransmittals.[Owner Document Number], tblTransmittals.[Int-Tr- NO], tbltransmittalNo.[Internal-Tr-Date]
FROM tblTransmittals INNER JOIN tbltransmittalNo
ON tblTransmittals.[Int-Tr- NO] = tbltransmittalNo.[Int-Tr-NO]
WHERE (((tbltransmittalNo.[Internal-Tr-Date])= '20171012'
I'm guessing that you want to return max(date) on each of the [Owner Document Number] and so I would do this:
SELECT A.[Owner Document Number], A.[Int-Tr- NO], B.[Internal-Tr-Date]
FROM tblTransmittals as A INNER JOIN tbltransmittalNo as B
ON A.[Int-Tr- NO] = B.[Int-Tr-NO]
JOIN
(SELECT C.[Owner Document Number], max(D.[Internal-Tr-Date])
FROM tblTransmittals as C INNER JOIN tbltransmittalNo as D
ON C.[Int-Tr-NO] = D.[Int-Tr-NO] GROUP BY C.[Owner Document Number]) AS E
ON A.[Owner Document Number] = E.[Owner Document Number]
and B.[Internal-Tr-Date] = E.[Internal-Tr-Date]
Good luck.
Related
This is based on AdventureWorks sample database.
And here is my query:
SELECT FirstName, LastName,
(SELECT COUNT(SalesOrderID)
FROM SalesOrderHeader
WHERE SalesOrderHeader.ContactID = Contact.ContactID) AS OrderCount
FROM Contact
ORDER BY OrderCount desc
Question: what should I add to my query so it only shows OrderCount that is more than 20? Nothing else should change about my output. I tried this and it did not work:
WHERE SalesOrderHeader.ContactID = Contact.ContactID AS OrderCount AND COUNT(SalesOrderID) > 20
Rewrite as a join aggregation query and then use HAVING:
SELECT
c.FirstName,
c.LastName,
COUNT(s.SalesOrderID) AD OrderCount
FROM Contacts c
INNER JOIN SalesOrderHeader s
ON c.ContactID = s.ContactID
GROUP BY
c.FirstName,
c.LastName
HAVING
COUNT(s.SalesOrderID) > 20;
My current query returns too many lines per Subject_ID, so I want to use ROW_NUMBER() to limit the resulting set to 1 line per Subject_ID. I've added this line to my SELECT statement:
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
But when I try to put WHERE rn = 1 anywhere in the FROM statement, I get the error:
Incorrect syntax near the keyword 'WHERE'
And when I try to change it to AND rn = 1 (and add it on to another AND/OR line) I get the error:
Invalid column name 'rn'
So my first question is: When I add a field to my SELECT statement using that ROW_NUMBER() line, what table does this column belong to? Do I need to append it to something like Table.rn? My second question is where should I put this rn = 1 line and how should I write it in?
Full query:
SELECT
Groups.Group_Name
, CT.Created
, CT.Subject_Id
INTO #temp
FROM SubjectZ_Task CT
INNER JOIN
SubjectZ_Task_Users On CT.SubjectZ_Task_Id = SubjectZ_Task_Users.SubjectZ_Task_Id
INNER JOIN
Groups ON Groups.Group_ID = SubjectZ_Task_Users.Group_Reference
WHERE Group_Name LIKE 'Team 1'
AND CT.Created >= '1/1/2019' AND CT.Created < DATEADD(Day,1,'12/31/2019')
GROUP BY Groups.group_name, CT.Created, CT.Subject_ID
SELECT
CT.Group_Name
, CT.Created
, CS.Topic_Start_Date
, CS.Subject_ID
, P.FirstName
, P.LastName
, CS.Subject_Match_ID
, SubjectX.Firstname AS SubjectX_firstname
, CS.SubjectY
, AEC.AEC AS Max_AEC
, SubjectX.Email_id As SubjectX_Email
, Phone.Phone
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
FROM #temp CT
LEFT JOIN QE_Topic_Summary CS ON CS.Subject_ID = CT.Subject_Id
AND (Topic_Status LIKE 'In Progress'
OR Topic_Status LIKE 'Pending')
AND CS.Topic_Start_Date >= DATEADD(Day,-60,CT.Created) AND CS.Topic_Start_Date <= DATEADD(Day,60,CT.Created)
INNER JOIN Subjects P ON P.Subject_ID = CS.Subject_ID
LEFT JOIN Subjects SubjectX ON SubjectX.Subject_ID = CS.SubjectX_ID
LEFT JOIN QE_TB_MAX_AEC AEC ON AEC.Subject_ID = CS.Subject_ID
INNER JOIN Subject_Identifiers PI ON PI.Subject_ID = P.Subject_ID
LEFT JOIN Subject_Identifiers PIP ON PIP.Subject_ID = SubjectX.Subject_ID
LEFT JOIN Subject_Phone Phone On Phone.Subject_ID = P.Subject_ID WHERE Phone.Voice = 1
drop table #temp
I don't see a reference to rn in your WHERE clause, but my guess is that you need to wrap it in another query like so:
SELECT *
FROM(
SELECT
CT.Group_Name
, CT.Created
, CS.Topic_Start_Date
, CS.Subject_ID
, P.FirstName
, P.LastName
, CS.Subject_Match_ID
, SubjectX.Firstname AS SubjectX_firstname
, CS.SubjectY
, AEC.AEC AS Max_AEC
, SubjectX.Email_id As SubjectX_Email
, Phone.Phone
, ROW_NUMBER() over(partition by CS.Subject_ID order by CS.Subject_ID) rn
FROM #temp CT
LEFT JOIN QE_Topic_Summary CS ON CS.Subject_ID = CT.Subject_Id
AND (Topic_Status LIKE 'In Progress'
OR Topic_Status LIKE 'Pending')
AND CS.Topic_Start_Date >= DATEADD(Day,-60,CT.Created) AND CS.Topic_Start_Date <= DATEADD(Day,60,CT.Created)
INNER JOIN Subjects P ON P.Subject_ID = CS.Subject_ID
LEFT JOIN Subjects SubjectX ON SubjectX.Subject_ID = CS.SubjectX_ID
LEFT JOIN QE_TB_MAX_AEC AEC ON AEC.Subject_ID = CS.Subject_ID
INNER JOIN Subject_Identifiers PI ON PI.Subject_ID = P.Subject_ID
LEFT JOIN Subject_Identifiers PIP ON PIP.Subject_ID = SubjectX.Subject_ID
LEFT JOIN Subject_Phone Phone On Phone.Subject_ID = P.Subject_ID
WHERE Phone.Voice = 1
)t
WHERE t.rn = 1
I need a query for [Contribution]. I used this query:
with ttt as
(
select
(DYG.U_StyleId)[DYG Style]
,Max(O1.CardCode) [Party Group Code],
MAX(O1.CardName) [Party Group Name]
,MAX(OR1.DocDate) [Date]
,sum(CONVERT(NUMERIC(15,2),(RDR1.PriceBefDi*RDR1.Quantity))) [JobAmount]
,CONVERT(NUMERIC(15,2),SUM(RDR1.Quantity)) [Mtr]
,CONVERT(NUMERIC(15,2),SUM(RDR1.U_Pcs))[Pcs]
,(select sum(RDR1.PriceBefDi*RDR1.Quantity) from RDR1) tqty
from
ORDR OR1
left join RDR1 on RDR1.DocEntry = OR1.DocEntry
left join OITM on RDR1.ItemCode = oitm.ItemCode
LEFT JOIN OCRD ON OCRD.CardCode = OR1.CardCode
LEFT JOIN OCRG ON OCRG.GroupCode = OCRD.GroupCode
LEFT JOIN OCRD O1 ON O1.U_BCode = OCRD.U_GrpCod
LEFT JOIN
( SELECT U_StyleId FROM RDR1 WHERE U_StyleId in
('BLOOM','BLOOMING','DYD','DYD-R','DYED','Ex.CLR.','RAINBOW'))
DYG ON DYG.U_StyleId = RDR1.U_StyleId
group by
DYG.U_StyleId
)
select
Style, [Party Group Code],
[Party Group Name], JobAmount,
(sum(JobAmount) / tqty * 100) [Contribution],
[Date], [Pcs]
from
ttt
group by
Style
I need Sum of last jobamount to divide it with above tqty.
But it shows this error.
'Column 'ttt.Party Group Code' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.'
Please help me with the query to get right [Contribution] amount.
Try this:
select Style,[Party Group Code],[Party Group Name],JobAmount,[Date],[Pcs],
100.0 * (sum(JobAmount) OVER (PARTITION BY Style))/tqty [Contribution]
from ttt;
I am learning window functions in sql server. I am using AdventrueWorks2012 database for practice. I want to calculate total number of sales and purchases for each item in the store.
The classic solution can be like
SELECT ProductID,
Quantity,
(SELECT Count(*)
FROM AdventureWorks.Purchasing.PurchaseOrderDetail
WHERE PurchaseOrderDetail.ProductID = p.ProductID) TotalPurchases,
(SELECT Count(*)
FROM AdventureWorks.Sales.SalesOrderDetail
WHERE SalesOrderDetail.ProductID = p.ProductID) TotalSales
FROM (SELECT DISTINCT ProductID,
Quantity
FROM AdventureWorks.Production.ProductInventory) p
Trying to convert to window functions gives me wrong results:
SELECT DISTINCT d.ProductID,
Quantity,
Count(d.ProductID)
OVER(
PARTITION BY d.ProductID) TotalPurchases,
Count(d2.ProductID)
OVER(
PARTITION BY d2.ProductID) TotalSales
FROM (SELECT DISTINCT ProductID,
Quantity
FROM AdventureWorks.Production.ProductInventory) p
INNER JOIN AdventureWorks.Purchasing.PurchaseOrderDetail d
ON p.ProductID = d.ProductID
INNER JOIN AdventureWorks.Sales.SalesOrderDetail d2
ON p.ProductID = d2.ProductID
ORDER BY d.ProductID
Why this is wrong? How can I correct it?
You should change INNER JOIN to LEFT JOIN
Because when you inner join, result will miss productid which from ProductInventory table does not have PurchaseOrderDetail or SalesOrderDetail.
I have a request I wasn't sure to handle. I was thinking of using PIVOT, but I wasn't sure if that would be the way to go.
I have the following Data:
EmployeeA, DepartmentB, 1/10/2010
EmployeeA, DepartmentA, 1/1/2000
EmployeeB, DepartmentC, 1/3/2011
They want output for only the employees that have been in different departments. Something that looks like this (order is important due to the dates):
EmployeeA, DepartmentA, DepartmentB
Any help is appreciated. For some reason, my mind isn't finding a good solution.
You can do this by doing a self JOIN on the table and then using a PIVOT to get the data in the format that you want:
SELECT *
FROM
(
SELECT t1.emp, t1.dept, t1.dt
FROM test t1
INNER JOIN test t2
ON t1.emp = t2.emp
AND t1.dept != t2.dept
) x
PIVOT
(
min(dt)
for dept in ([A], [B], [C], [D], [E])
) p
See SQL Fiddle with Demo
If you remove the JOIN you will get all records, but you stated you only want the records that have been in more than one department.
Here's the answer I got which I got largely based on your work. Pivot doesn't work because I don't know the categories (in this case Department) ahead of time and I can only have two of them.
Maybe there's an easier way. I didn't use a CTE, because I believe this should work for Sybase as well which I don't think supports that.
select Meta1.[Employee ID],
Meta1.Department as PreviousDepartment,
Meta2.Department as CurrentDepartment
from
(
SELECT t1.[First Name], t1.[Last Name],
t1.[Employee ID], t1.Department, t1.[Hire Date],
ROW_NUMBER() over(PARTITION by t1.[EMPLOYEE ID] order by t1.[Hire Date]) as RowNum
FROM EMPLOYEE t1
INNER JOIN EMPLOYEE t2
ON t1.[Employee ID] = t2.[Employee ID]
AND t1.Department != t2.Department
) Meta1
inner join
(
SELECT t1.[Employee ID], t1.Department, t1.[Hire Date],
ROW_NUMBER() over(PARTITION by t1.[EMPLOYEE ID] order by t1.[Hire Date]) as RowNum
FROM EMPLOYEE t1
INNER JOIN EMPLOYEE t2
ON t1.[Employee ID] = t2.[Employee ID]
AND t1.Department != t2.Department
) Meta2
on Meta1.[Employee ID]=Meta2.[Employee ID]
where Meta1.RowNum=1
and Meta2.RowNum=2