SQL Server识别时间戳之间的间隙并输出分别标记它们

时间:2018-08-23 12:37:14

标签: sql sql-server

我有带有ID和时间戳的数据集。

我想输出间隔大于或等于20分钟的每个间隔。

样本数据:

IDID timerecord
1    2018-02-26 06:40:28.483
2    2018-02-26 06:42:03.967
3    2018-02-26 06:44:07.277
4    2018-02-26 06:47:25.913
5    2018-02-26 07:04:23.290
6    2018-02-26 10:19:25.063
7    2018-02-26 10:19:57.750
8    2018-02-26 10:21:45.547
9    2018-02-26 10:24:14.297
10   2018-02-26 10:28:17.967
11   2018-02-26 10:30:10.907
12   2018-02-26 10:30:20.627
13   2018-02-26 10:41:39.717
14   2018-02-26 10:43:00.247
15   2018-02-26 10:45:00.120
16   2018-02-26 10:47:13.867
17   2018-02-26 10:49:36.727
18   2018-02-26 17:06:30.333
19   2018-02-26 17:07:55.550
20   2018-02-26 17:09:37.520
21   2018-02-26 17:16:49.487

SQL小提琴:http://sqlfiddle.com/#!18/42efe/1/0

预期输出:

timestart               timeend
2018-02-26 06:40:28.483 2018-02-26 07:04:23.290
2018-02-26 10:19:25.063 2018-02-26 10:49:36.727
2018-02-26 17:06:30.333 2018-02-26 17:16:49.487

2 个答案:

答案 0 :(得分:1)

使用na.rm来确定组的起始位置。然后进行累加和分配一个组。和聚合:

melt(setDT(dx),na.rm=TRUE)

Here是SQL Fiddle。

答案 1 :(得分:1)

使用lag()累积方法:

SELECT MIN(timerecord), MAX(timerecord)
FROM (SELECT *, SUM(CASE WHEN DIFF_MN > 20 THEN 1 ELSE 0 END) OVER (ORDER BY IDID) GRP
      FROM (SELECT *, DATEDIFF(MINUTE, LAG(timerecord) OVER (ORDER BY IDID), timerecord) AS DIFF_MN 
            FROM Mytable 
           ) T
     ) T
GROUP BY GRP;

这里是Demo