SQL Old&新的价值观和时间差异

时间:2014-12-17 11:04:17

标签: sql-server

我有查询,提供以下结果。

    WORK_ITEM_ID    WORK_ITEM_STA_CD    CREAT_TS
    1                   8               2014-12-17 16:20:06.250
    1                   9               2014-12-17 16:23:48.430
    2                   8               2014-12-17 16:20:06.250
    2                   9               2014-12-17 16:24:36.930
    3                   8               2014-12-17 16:20:06.250
    4                   8               2014-12-17 16:20:06.250
    5                   8               2014-12-17 16:20:06.250

我希望将新列作为OLD_STA_CD&时差得到如下结果。任何人都可以指导我这样做。

    WORK_ITEM_ID  OLD_STA_CD    WORK_ITEM_STA_CD    CREAT_TS               TimeDifference
    1               null            8           2014-12-17 16:20:06.250    
    1               8               9           2014-12-17 16:23:48.430    Thisrow - Previous Row
    2               null            8           2014-12-17 16:20:06.250
    2               8               9           2014-12-17 16:24:36.930    Thisrow - Previous Row
    3               null            8           2014-12-17 16:20:06.250
    4               null            8           2014-12-17 16:20:06.250
    5               null            8           2014-12-17 16:20:06.250                             

1 个答案:

答案 0 :(得分:1)

使用Window FunctionLeft join

;WITH cte
     AS (SELECT Row_number()OVER(partition BY WORK_ITEM_ID ORDER BY CREAT_TS ) rn,
                *
         FROM   tablename)
SELECT a.WORK_ITEM_ID,
       OLD_STA_CD= b.WORK_ITEM_STA_CD,
       a.WORK_ITEM_STA_CD,
       a.CREAT_TS,
       Time_Diff_In_Seconds=Datediff(ss, b.CREAT_TS, a.CREAT_TS)
FROM   cte a
       LEFT JOIN cte b
              ON a.WORK_ITEM_ID = b.WORK_ITEM_ID
                 AND a.rn = b.rn + 1 

如果您使用Sql Server 2012+使用LAG Function来获取上一行

SELECT WORK_ITEM_ID,
       OLD_STA_CD=Lag(WORK_ITEM_STA_CD)OVER(partition BY WORK_ITEM_ID ORDER BY CREAT_TS ),
       WORK_ITEM_STA_CD,
       CREAT_TS,
       Time_Diff_In_Seconds=Datediff(ss, Lag(CREAT_TS)OVER(partition BY WORK_ITEM_ID ORDER BY CREAT_TS ), CREAT_TS)
FROM   Tablename