sql中的行明智差异

时间:2018-09-12 10:03:53

标签: sql sql-server

+ --------+----------+----------------+
| case_id | activity | end_time       |
+ --------+----------+----------------+
| 1       | A        | 1/1/2011 00:37 |
| 1       | B        | 1/1/2011 12:09 |
| 1       | C        | 1/3/2011 03:37 |
| 1       | D        | 1/3/2011 11:21 |
| 1       | E        | 1/3/2011 19:10 |
| 1       | F        | 1/4/2011 15:31 |
| 2       | G        | 1/1/2011 12:39 |
| 2       | A        | 1/1/2011 00:29 |
| 2       | B        | 1/1/2011 15:40 |
| 2       | C        | 1/4/2011 14:53 |
| 2       | D        | 1/4/2011 23:02 |
| 2       | E        | 1/5/2011 09:04 |
| 2       | F        | 1/6/2011 06:32 |
| 3       | H        | 1/2/2011 02:03 |
| 3       | A        | 1/1/2011 03:03 |
| 3       | B        | 1/2/2011 15:55 |
| 3       | C        | 1/5/2011 14:20 |
| 3       | D        | 1/5/2011 21:55 |
| 3       | E        | 1/6/2011 13:47 |
| 3       | F        | 1/7/2011 16:31 |
+ --------+----------+----------------+

预期结果

+ --------+----------+----------------+--------------------------------------+
| case_id | activity | end_time       | diff in sec                          |
+ --------+----------+----------------+--------------------------------------+
| 1       | A        | 1/1/2011 00:37 | 41520(row 1 end_time-row 2 end_time) |
| 1       | B        | 1/1/2011 12:09 | 30720                                |
| 1       | C        | 1/3/2011 03:37 | 27840
+ --------+----------+----------------+--------------------------------------+

2 个答案:

答案 0 :(得分:1)

我想您正在寻找类似的东西

SELECT 
    case_id, 
    activity, 
    end_time, 
    DATEDIFF( SECOND, end_time, LEAD(end_time) OVER (ORDER BY case_id, activity))
FROM your_table
ORDER BY case_id, activity

但是LEAD函数仅自SQL Server 2012起可用。您没有提到使用的版本。

答案 1 :(得分:0)

您可以尝试

SELECT 
    case_id, 
    activity, 
    end_time, 
    DATEDIFF( SECOND, end_time, NextRow)
FROM your_table as CurrentRow
outer apply (select top  1 end_time from your_table  as x where x.Identit_Field > CurrentRow.IdentityField) as NextRow