SQL Calculate Days between two dates in one table

假装没事ソ 提交于 2020-01-24 05:54:05

问题


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.


回答1:


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




回答2:


You must select 1st and 2nd records that you want, then get their dates and get DATEDIFF of those two dates.

DATEDIFF(date1, date2);




回答3:


Your problem is getting the next member date.

Here is an example using a correlated subquery to get the next date:

select t.*, datediff(day, t.transfer_date, nextdate) as Days_Between
from (select t.*,
             (select min(transfer_date)
              from trans t2
              where t.bd_id = t2.bd_id and
                    t.member_id = t2.member_id and
                    t.transfer_date < t2.transfer_date
             ) as NextDate
      from trans t
     ) t

SQL Server 2012 has a function called lag() that makes this a bit easier to express.



来源:https://stackoverflow.com/questions/12007857/sql-calculate-days-between-two-dates-in-one-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!