如何根据某些条件按SQL分组?

时间:2015-05-06 12:10:25

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

我正在使用Microsoft SQL Server 2014,我有关于观看电视的人的以下数据:

时间是从午夜开始的几分钟。

PersonId   StartTime  EndTime
1          300        600
1          250        700
1          200        800
1          900        1200
2          100        200

现在你可以看到,我想要的是人1的查看语句分组如下:

250 - 700与300 - 600重叠,所以我想要做的是从开始时间开始最小值,从结束时间开始最大值,因为它们重叠,我想对人1的所有查看语句执行此操作。但是我怎么能和一个小组一起做?

由于

1 个答案:

答案 0 :(得分:5)

峡谷和群岛

DECLARE @TVWatchingTime TABLE (PersonId int, StartTime int, EndTime int)
INSERT INTO @TVWatchingTime 
VALUES 
(1,          300,        600),
(1,          250,        700),
(1,          200,        800),
(1,          900,        1200),
(2,          100,        200)

;WITH cteSource(PersonId, StartTime, EndTime)
AS 
(
    SELECT
        s.PersonId, s.StartTime, e.EndTime
    FROM        
    (
        SELECT  PersonId, StartTime, ROW_NUMBER() OVER (ORDER BY StartTime) AS rn
        FROM    @TVWatchingTime
    ) AS s
    INNER JOIN 
    (
        SELECT  PersonId, EndTime, ROW_NUMBER() OVER (ORDER BY EndTime) + 1 AS rn
        FROM    @TVWatchingTime
    ) AS e ON s.PersonId = e.PersonId AND e.rn = s.rn
    WHERE s.StartTime > e.EndTime

    UNION ALL

    SELECT PersonId, MIN(StartTime), MAX(EndTime)
    FROM    @TVWatchingTime
    GROUP BY PersonId
), cteGrouped(PersonId, theTime, grp)
AS (
    SELECT  PersonId, u.theTime,
        (ROW_NUMBER() OVER (ORDER BY u.theTime) - 1) / 2
    FROM    cteSource AS s
    UNPIVOT (
            theTime
            FOR theColumn IN (s.StartTime, s.EndTime)
        ) AS u
)
SELECT PersonId, MIN(theTime) StartTime, MAX(theTime) EndTime
FROM cteGrouped
GROUP BY PersonId, grp
ORDER BY PersonId, grp

返回:

PersonId    StartTime   EndTime
1           200         800
1           900         1200
2           100         200