计算两个连续行之间的日期差异

时间:2016-05-17 07:52:18

标签: sql sql-server sql-server-2012

我有一个包含日期时间行的表格,如下所示。

ID | DateTime

1  | 12:00
2  | 12:02
3  | 12:03
4  | 12:04
5  | 12:05
6  | 12:10

我想识别行之间存在5分钟“间隙”的行(例如,第5行和第6行)。

我知道我们需要使用DATEDIFF,但我怎样才能获得彼此连续的那些行?

3 个答案:

答案 0 :(得分:5)

您可以使用LAGLEAD窗口函数:

SELECT ID
FROM (
  SELECT ID, [DateTime], 
         DATEDIFF(mi, LAG([DateTime]) OVER (ORDER BY ID), [DateTime]) AS prev_diff,
         DATEDIFF(mi, [DateTime], LEAD([DateTime]) OVER (ORDER BY ID)) AS next_diff
  FROM mytable) AS t
WHERE prev_diff >= 5 OR next_diff >= 5

<强>输出:

ID
==
5
6

注意:以上查询假定订单由ID字段定义。您可以轻松地将此字段替换为指定表中顺序的任何其他字段。

答案 1 :(得分:0)

更新SS2012:使用LAG

DECLARE @tbl TABLE(ID INT, T TIME)
INSERT INTO @tbl VALUES
 (1,'12:00')
,(2,'12:02')
,(3,'12:03')
,(4,'12:04')
,(5,'12:05')
,(6,'12:10');

WITH TimesWithDifferenceToPrevious AS
(
    SELECT ID
          ,T
          ,LAG(T) OVER(ORDER BY T) AS prev
          ,DATEDIFF(MI,LAG(T) OVER(ORDER BY T),T) AS MinuteDiff
    FROM @tbl
)
SELECT *
FROM TimesWithDifferenceToPrevious
WHERE ABS(MinuteDiff) >=5

结果

6   12:10:00.0000000    12:05:00.0000000    5

答案 2 :(得分:0)

你可能会尝试这个(我不确定它是否真的很快)

SELECT current.datetime  AS current_datetime,
       previous.datetime AS previous_datetime,
       DATEDIFF(minute, previous.datetime, current.datetime) AS gap
FROM   my_table current
JOIN   my_table previous
  ON   previous.datetime < current.datetime
 AND   NOT EXISTS (SELECT *
                   FROM   my_table others
                   WHERE  others.datetime < current.datetime
                     AND  others.datetime > previous.datetime);