SQL创建其他列值相同的时间间隔

时间:2018-03-26 15:23:36

标签: sql sql-server tsql sql-server-2014

我有一个SQL Server表,用于存储具有datetime的事件,如下所示:

ES  TimeStamp
----------------------------
1   2018-03-05 00:00:12.000
1   2018-03-05 00:00:32.000
0   2018-03-05 00:00:52.000
0   2018-03-05 00:01:12.000
1   2018-03-05 00:01:32.000
1   2018-03-05 00:01:52.000
0   2018-03-05 00:02:12.000
0   2018-03-05 00:02:32.000
0   2018-03-05 00:02:52.000
0   2018-03-05 00:03:12.000
1   2018-03-05 00:03:32.000
1   2018-03-05 00:03:52.000
1   2018-03-05 00:04:12.000

我正在寻找一种从我的桌子中选择的快捷方式:

ES   StartTimeStamp             EndTimeStamp
-------------------------------------------------------
1    2018-03-05 00:00:12.000    2018-03-05 00:00:32.000
0    2018-03-05 00:00:52.000    2018-03-05 00:01:12.000
1    2018-03-05 00:01:32.000    2018-03-05 00:01:52.000
0    2018-03-05 00:02:12.000    2018-03-05 00:03:12.000
1    2018-03-05 00:03:32.000    2018-03-05 00:04:12.000

2 个答案:

答案 0 :(得分:3)

您可以使用Gaps and Islands解决方案。

SELECT ES, MIN([TimeStamp]) StartTimeStamp, MAX([TimeStamp]) EndTimeStamp FROM 
    (SELECT *, 
        GRP = ROW_NUMBER() OVER(ORDER BY [TimeStamp]) - 
            ROW_NUMBER() OVER(PARTITION BY ES ORDER BY [TimeStamp])  FROM @MyTable) AS T
GROUP BY ES, GRP

示例数据:

DECLARE @MyTable TABLE (ES INT ,[TimeStamp] DATETIME)
INSERT INTO @MyTable VALUES
(1, '2018-03-05 00:00:12.000'),
(1, '2018-03-05 00:00:32.000'),
(0, '2018-03-05 00:00:52.000'),
(0, '2018-03-05 00:01:12.000'),
(1, '2018-03-05 00:01:32.000'),
(1, '2018-03-05 00:01:52.000'),
(0, '2018-03-05 00:02:12.000'),
(0, '2018-03-05 00:02:32.000'),
(0, '2018-03-05 00:02:52.000'),
(0, '2018-03-05 00:03:12.000'),
(1, '2018-03-05 00:03:32.000'),
(1, '2018-03-05 00:03:52.000'),
(1, '2018-03-05 00:04:12.000')

结果:

ES          StartTimeStamp          EndTimeStamp
----------- ----------------------- -----------------------
1           2018-03-05 00:00:12.000 2018-03-05 00:00:32.000
0           2018-03-05 00:00:52.000 2018-03-05 00:01:12.000
1           2018-03-05 00:01:32.000 2018-03-05 00:01:52.000
0           2018-03-05 00:02:12.000 2018-03-05 00:03:12.000
1           2018-03-05 00:03:32.000 2018-03-05 00:04:12.000

答案 1 :(得分:1)

您可以使用LAG创建组,然后按子查询分组将获得期望。

SELECT  t.ES ,
        MIN(t.TimeStamp) AS 'StartTimeStamp' ,
        MAX(t.TimeStamp) AS 'EndTimeStamp'
FROM    ( SELECT    * ,
                    MAX(flag) OVER ( ORDER BY t.TimeStamp ) rn
          FROM      ( SELECT    * ,
                                CASE WHEN t.ES = LAG(t.ES) OVER ( ORDER BY TimeStamp )
                                     THEN 0
                                     ELSE t.id
                                END flag
                      FROM      ( SELECT    * ,
                                            ROW_NUMBER() OVER ( ORDER BY TimeStamp ) AS id
                                  FROM      T
                                ) AS t
                    ) AS t
        ) AS t
GROUP BY t.es ,
        t.rn

SQLFiddle