I have the following PIVOTING
query:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET NOCOUNT ON
SET DEADLOCK_PRIORITY LOW
SELECT *
FROM (select jsc.applicationid
,[the date of change]=MIN(jsc.changedate)
--,jsc.[oldStatus]
,jsc.[newStatus]
,C1.countryName
,[Name] = ja.firstname + COALESCE(' ' + JA.LASTNAME, '')
,nationality=C2.countryName
,[Agency Name] = a.name
from dbo.applicationStateChange jsc
INNER JOIN dbo.application app
ON app.applicationID = jsc.applicationID
INNER JOIN dbo.applicant ja
ON ja.applicantID= app.applicantID
INNER JOIN dbo.agency a
ON a.agencyID = app.agencyID
INNER JOIN dbo.country C1
ON C1.countryCode = ja.countrycode
INNER JOIN dbo.country C2
ON C2.countryCode = ja.nationalitycode
WHERE 1=1
-- AND jsc.[oldStatus] = 'OLA'
AND jsc.[newStatus] IN ('OLA', 'AWA', 'TBM')
--AND ja.countrycode = 'GB'
AND YEAR(jsc.changedate) >= 2010
GROUP BY jsc.applicationid
--,jsc.changedate
--,jsc.[oldStatus]
,jsc.[newStatus]
,C1.countryName
,ja.firstname
,JA.LASTNAME
,C2.countryName
,a.name
) RADHE
PIVOT (MIN([the date of change]) for [newStatus] IN ([OLA], [AWA], [TBM]) ) as KRISHNA
WHERE 1=1
AND [OLA] IS NOT NULL
AND [AWA] IS NOT NULL
AND [TBM] IS NOT NULL
ORDER BY applicationid
That gives me results like these:
Question:
How could I calculate X and Y on the above picture and display the result there?
X – should be the amount of time (ok it can be number of days to keep it simple
) between AWA
and OLA
.
Y – should be the amount of time (ok it can be number of days to keep it simple
) between TBM
and AWA
.
Best Answer
Let me know if this produce the desired result.
First I've set up an example on dbfiddle that returns unpivot data similar to the result of your question.
Then I enclosed your pivot query inside a CTE function, and finally it calculates datediff using data returned by pivot query.
This is the final result:
dbfiddle here