根据SQL中多行的位置创建开始和停止日期

时间:2016-05-30 07:34:51

标签: sql sql-server

  MRN    LocationGUID   transferdate
    123    209300610    2016-05-16 00:51:00.000
    123    209100610    2016-05-17 13:58:32.000
    123    148900610    2016-05-20 23:55:28.000
    456    853698742    2016-05-01 08:15:00.000
    456    951357782    2016-05-03 14:32:28.000

我的桌子看起来像上面的那个,我需要做的是让它看起来像下面的

MRN locationGUID  Transferdate                   Transferstop
123 209300610      2016-05-16 00:51:00.000       2016-05-17 13:58:32.000
123 209100610      2016-05-17 13:58:32.000       2016-05-20 23:55:28.000
123 148900610      2016-05-20 23:55:28.000       GETDATE()
456 853698742      2016-05-01 08:15:00.000       2016-05-03 14:32:28.000

1 个答案:

答案 0 :(得分:0)

如果您使用的是SQL Server 2012+,则可以使用LEAD窗口函数:

SELECT LocationGUID, 
       CAST(Transferdate AS DATE) AS Transferdate, 
       CAST(COALESCE(LEAD(transferdate) OVER 
                     (ORDER BY transferdate), GETDATE()) AS DATE) AS Transferstop
FROM mytable

Demo here

注意:如果您想留出时间,可以直接从查询中省略CASTDATE