Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Calculate Days between two dates in one table

Tags:

sql

tsql

I have a table dbo.Trans which contains an id called bd_id(varchar) and transfer_date(Datetime), also an identifier member_id pk is trns_id and is sequential

Duplicates of bd_id and member_id exist in the table.

transfer_date       |bd_id| member_id | trns_id
2008-01-01 00:00:00 | 432 | 111       | 1  
2008-01-03 00:00:00 | 123 | 111       | 2  
2008-01-08 00:00:00 | 128 | 111       | 3  
2008-02-04 00:00:00 | 123 | 432       | 4
.......

For each member_id, I want to get the amount of days between dates and for each bd_id

E.G., member 111 used 432 from 2008-01-01 until 2008-02-01 so return should be 2
Then next would be 5

I know the DATEDIFF() function exists but I am not sure how to get the difference when dates are in the same table.

Any help appreciated.

like image 500
k1f1 Avatar asked Dec 11 '22 23:12

k1f1


1 Answers

You could try something like this.

select T1.member_id,
       datediff(day, T1.transfer_date, T3.transfer_date) as DD
from YourTable as T1
  cross apply (select top 1 T2.transfer_date
               from YourTable as T2
               where T2.transfer_date > T1.transfer_date and
                     T2.member_id = T1.member_id
               order by T2.transfer_date) as T3

SE-Data

like image 50
Mikael Eriksson Avatar answered Jan 05 '23 08:01

Mikael Eriksson