Calculate date difference of 2 consecutive rows

ukerandi
ukerandi used Ask the Experts™
on
Hi Experts,

I need to calculate date changes in the row see atatched excel file  and see expected resuts in the output column

Any idea much appriciated

My code
SELECT 
pos.PositionName,
candstrm.candidate_Id,

MIN(candstrm.entered_previous_stage) AS [DateChanged],
candstrm.stage,
ROW_NUMBER() OVER (ORDER BY MIN(candstrm.entered_previous_stage)) AS rowNumber
FROM tblcandidateStream candstrm
LEFT OUTER JOIN tblPosition pos ON candstrm.positionID=pos.PositionID
WHERE candstrm.positionID='5f7a66749c5401' AND candstrm.candidate_Id='10299ef86c0601'
AND candstrm.stage<>''

--ORDER BY  candstrm.streamtimestamp,candstrm.entered_previous_stage

GROUP BY pos.PositionName,candstrm.candidate_Id,candstrm.stage

Open in new window

helpsql.xlsx
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
ste5anSenior Developer

Commented:
Well, nowadays you use normally LAG() to get this value.
Most Valuable Expert 2012
Distinguished Expert 2018
Commented:
Yes, use LAG.

Based on a simple table from your sample data:
select PositionName, candidate_Id,
	DateChanged,
	datediff(second,lag(DateChanged) over(order by DateChanged),DateChanged)/86400.0 Output,
	stage,
	row_number() over(order by DateChanged) rowNumber
from tab1;

Open in new window


Working test case here:
https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=655ddc271c597adb5fbf9b42e8d9dcaf

Author

Commented:
thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial