Hvis du bruger SQLServer 2012 eller bedre, kan du bruge LAG
for at få den forrige værdi af en kolonne, derefter SUM() OVER (ORDER BY ...)
at oprette en rullende sum, i dette tilfælde en, der tæller ændringen af CourseName, der kan bruges som GROUP BY
anker
With A AS (
SELECT ClassRoom
, CourseName
, StartTime
, EndTime
, PrevCourse = LAG(CourseName, 1, CourseName) OVER (ORDER BY StartTime)
FROM Table1
), B AS (
SELECT ClassRoom
, CourseName
, StartTime
, EndTime
, Ranker = SUM(CASE WHEN CourseName = PrevCourse THEN 0 ELSE 1 END)
OVER (ORDER BY StartTime, CourseName)
FROM A
)
SELECT ClassRoom
, CourseName
, MIN(StartTime) StartTime
, MAX(EndTime) EndTime
FROM B
GROUP BY ClassRoom, CourseName, Ranker
ORDER BY StartTime