Search code examples
sqldatetimesubqueryinner-joinwindow-functions

Selecting the difference between dates in a stored procedure using a subquery


I can't get my head around whether this is even possible, but I feel like I might have done it before and lost that bit of code. I am trying to craft a select statement that contains an inner join on a subquery to show the number of days between two dates from the same table.

A simple example of the data structure would look like:

Name  ID  Date    Day       Hours
Bill  1   3/3/20  Thursday   8
Fred  2   4/3/20  Monday     6
Bill  1   8/3/20  Tuesday    2

Based on this data, I want to select each row plus an extra column which is the number of days between the date from each row for each ID. Something like:

Select * from tblData
Inner join (datediff(Select Top(1) Date from tblData where Date < Date), Date) And ID = ID) 

or for simplicity:

Select * from tblData
Inner join (datediff(Select Top(1) Date from tblData where Date < 8/3/20), 8/3/20) And ID = 1)

The resulting dataset would look like:

Name  ID  Date    Day       Hours  DaysBtwn
Bill  1   3/3/20  Thursday   8     4 (Assuming there was an earlier row in the table)
Fred  2   4/3/20  Monday     6     5 (Assuming there was an earlier row in the table)
Bill  1   8/3/20  Tuesday    2     5 (Based on the previous row date being 3/3/20 for Bill)

Does this make sense and am I trying to do this the wrong way? I want to do this for about 600000 rows in table and therefore efficiency is the key, so if there is a better way to do this, i'm open to suggestions.


Solution

  • You can use lag():

    select t.*, datediff(day, lag(date) over(partition by id order by date), date) diff
    from mytable t