在SQL中对连续的时间间隔进行分组

时间:2015-12-18 15:04:15

标签: sql sql-server time intervals

我有类似的东西

+------+-----+-----------+---------+
| Room | Day | StartTime | EndTime |
+------+-----+-----------+---------+
| 1    | 1   | 08:00     | 09:00   |
+------+-----+-----------+---------+
| 1    | 1   | 09:00     | 10:00   |
+------+-----+-----------+---------+
| 1    | 1   | 13:00     | 14:00   |
+------+-----+-----------+---------+
| 2    | 2   | 07:00     | 08:00   |
+------+-----+-----------+---------+

我想按房间,日期和时间间隔进行分组,但只是连续的时间间隔,例如:

+------+-----+-----------+---------+
| Room | Day | StartTime | EndTime |
+------+-----+-----------+---------+
| 1    | 1   | 08:00     | 10:00   |
+------+-----+-----------+---------+
| 1    | 1   | 13:00     | 14:00   |
+------+-----+-----------+---------+
| 2    | 2   | 07:00     | 08:00   |
+------+-----+-----------+---------+

我有这段代码,但我不满意,因为它也是对差距进行分组并引发以下结果:

SELECT
sd.Cod_Room,
sd.Cod_Day,
MIN(bd.StartTime) as StartTime,
MAX(bd.EndTime) as EndTime
FROM
Schedule.ScheduleDetail AS sd
INNER JOIN Schedule.BlockDetail AS bd ON sd.Cod_BlockDetail = bd.Cod_BlockDetail
GROUP BY
sd.Room, sd.Day

+------+-----+-----------+---------+
| Room | Day | StartTime | EndTime |
+------+-----+-----------+---------+
| 1    | 1   | 08:00     | 14:00   |
+------+-----+-----------+---------+
| 2    | 2   | 07:00     | 08:00   |
+------+-----+-----------+---------+

我正在阅读有关铅()和滞后()的信息,但它花了我比我想象的更多的时间。 感谢您的帮助

1 个答案:

答案 0 :(得分:3)

您可以通过识别重叠的组然后累积此值来定义组来完成此操作。以下假定SQL Server 2012 +:

with t as (
      select sd.Cod_Room, sd.Cod_Day, bd.StartTime, bd.EndTime
      from Schedule.ScheduleDetail sd INNER JOIN
           Schedule.BlockDetail bd
           ON sd.Cod_BlockDetail = bd.Cod_BlockDetail
     )
select cod_room, cod_day,
       min(startTime) as startTime, max(endTime) as endTime
from (select t.*,
             sum(IsStart) over (partition by cod_room, cod_day order by StartTime) as grp
      from (select t.*, 
                   (case when StartTime = lag(EndTime) over (partition by cod_room, cod_day order by StartTime)
                         then 0 else 1
                    end) as IsStart
            from t
           ) t
     ) t
group by cod_room, cod_day, grp;