# Calculate date difference of 2 consecutive rows

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
helpsql.xlsx
Comment
Watch Question

Do more with

EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior 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;

Working test case here: