I am trying to calculate the difference in days between dates for consecutive rows in a single column called Date_col
. I then want to put those differences into a new column called Expected_Results.
I have the following code so far:
DECLARE @datedifferences DATETIME
SET @datedifferences = (SELECT DATEDIFF(DAY, MIN(Date_col), MAX(Date_col)) FROM Schema.Table)
SELECT DISTINCT TOP 100 Date_col
FROM Database.Schema.Table
WHERE Date_col = @datedifferences
ORDER BY Date_col
The below is what I'd like to have returned:
Date_col Expected_Results
1/1/2018 --
2/2/2018 31
3/3/2018 31
4/4/2018 31
5/5/2018 31
6/6/2018 31
7/7/2018 31
8/8/2018 31
However, the query runs successfully but nothing is returned. I suspect this is because I'm missing some kind of loop to iterate over the rows. How can I incorporate a while loop into query to successfully iterate over the rows such that the query prints the expected results?