如何为列字段获取两行之间的差异?当列是时间戳时

时间:2016-05-25 18:36:11

标签: sql sql-server

我找到了关于为列字段(https://stackoverflow.com/questions/634568/how-to-get-difference-between-two-rows-for-a-column-field#=)获取两行差异的可能性的答案

我的问题是,当Value是时间戳时,我怎么能做同样的事情?我正在使用SQL Server 2012。

表格如下图所示

Basically, what I want to do is to get the difference between two consecutive timestamps to see after how much time, a new DMC went through the process

希望现在更清楚。我对此非常陌生。

提前谢谢。

1 个答案:

答案 0 :(得分:0)

由于您使用的是SQL Server 2012,因此现在可以使用LAG / LEAD从上一行/下一行获取列的值。然后,您只需计算同一行中两列之间的差异。像这样:

create table YOUR_TABLE(ID integer, DT datetime);
insert into YOUR_TABLE
    select 2, '02/02/2016 12:00:00' union all
    select 3, '02/05/2016 12:00:00' union all
    select 4, '02/06/2016 12:00:00' union all
    select 5, '02/07/2016 12:00:00' 
;

select 
    ID,
    DT,
    datediff(day, DT, lead(DT) over (order by ID)) as DIFF
from your_table;