2015-12-18 118 views
1

我有這樣的事情分組連續時間間隔

+------+-----+-----------+---------+ 
| 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 | 
+------+-----+-----------+---------+ 

我正在閱讀有關lead()和lag()的內容,但是這比我想象的要耗費更多的時間。 感謝您的幫助

+0

您使用的是哪個版本的sql server? – JamieD77

+0

@ JamieD77我正在使用2014 –

回答

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; 
+0

非常好!它完美無瑕! –