My data looks like the following
TicketID OwnedbyTeamT Createddate ClosedDate 1234 A 1234 A 01/01/2019 01/05/2019 1234 A 10/05/2018 10/07/2018 1234 B 10/04/2019 10/08/2018 1234 finance 11/01/2018 11/11/2018 1234 B 12/02/2018
Now, I want to calculate the datediff between the closeddates for teams A, and B, if the max closeddate for team A is greater than max closeddate team B. If it is smaller or null I don’t want to see them. So, for example,I want to see only one record like this :
TicketID (Datediff)result-days 1234 86
and for another tickets, display the info. For example, if the conditions aren’t met then:
TicketID (Datediff)result-days 2456 -1111111
Data sample for 2456:
TicketID OwnedbyTeamT Createddate ClosedDate 2456 A 2456 A 10/01/2019 10/05/2019 2456 B 08/05/2018 08/07/2018 2456 B 06/04/2019 06/08/2018 2456 finance 11/01/2018 11/11/2018 2456 B 12/02/2018
I want to see the difference in days between 01/05/2019 for team A, and
10/08/2018 for team B.
Here is the query that I wrote, however, all I see is -1111111, any help please?:
SELECT A.incidentid, ( CASE WHEN Max(B.[build validation]) <> 'No data' AND Max(A.crfs) <> 'No data' AND Max(B.[build validation]) < Max(A.crfs) THEN Datediff(day, Max(B.[build validation]), Max(A.crfs)) ELSE -1111111 END ) AS 'Days-CRF-diff' FROM (SELECT DISTINCT incidentid, Iif(( ownedbyteam = 'B' AND titlet LIKE '%Build validation%' ), Cast( closeddatetimet AS NVARCHAR(255)), 'No data') AS 'Build Validation' FROM incidentticketspecifics) B INNER JOIN (SELECT incidentid, Iif(( ownedbyteamt = 'B' OR ownedbyteamt = 'Finance' ), Cast( closeddatetimet AS NVARCHAR(255)), 'No data') AS 'CRFS' FROM incidentticketspecifics GROUP BY incidentid, ownedbyteamt, closeddatetimet) CRF ON A.incidentid = B.incidentid GROUP BY A.incidentid
Advertisement
Answer
Your sample query is quite complicated and has conditions not mentioned in the text. It doesn’t really help.
I want to calculate the datediff between the closeddates for teams A, and B, if the max closeddate for team A is greater than max closeddate team B. If it is smaller or null I don’t want to see them.
I think you want this per TicketId
. You can do this using conditional aggregation:
SELECT TicketId, DATEDIFF(day, MAX(CASE WHEN OwnedbyTeamT = 'B' THEN ClosedDate END), MAX(CASE WHEN OwnedbyTeamT = 'A' THEN ClosedDate END) as diff ) FROM incidentticketspecifics its GROUP BY TicketId HAVING MAX(CASE WHEN OwnedbyTeamT = 'A' THEN ClosedDate END) > MAX(CASE WHEN OwnedbyTeamT = 'B' THEN ClosedDate END)