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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With