hm ... a very interesting task. I got the following results:
Type IntervalBegin CurrEnd 1 10 20 1 NULL 23 2 24 28 1 29 40 2 41 47 2 NULL 50 2 75 80 1 81 100 1 NULL 10 1 10 20
but I'm still puzzled by the aggregation of the results ...
request below
DECLARE @MyTable TABLE ([Id] INT, [Type] INT, [Begin] INT, [End] INT) INSERT INTO @MyTable([Id], [Type], [Begin], [End] ) VALUES (1, 1, 10, 20), (2, 1, 21, 23), (3, 2, 24, 28), (4, 1, 29, 40), (5, 2, 41, 47), (6, 2, 48, 50), (7, 2, 75, 80), (8, 1, 81, 100), (9, 1, 0, 10), (10, 1, 10, 20) SELECT [Type], CASE WHEN ShouldCompareWithPrevious = 1 AND PrevBegin IS NULL THEN CurrBegin WHEN ShouldCompareWithPrevious = 1 AND PrevEnd = 100 AND CurrBegin = 0 THEN NULL WHEN ShouldCompareWithPrevious = 1 AND PrevEnd + 1 <> CurrBegin THEN CurrBegin WHEN ShouldCompareWithPrevious = 0 THEN CurrBegin ELSE NULL END IntervalBegin, CurrEnd FROM ( SELECT t1.[Id], t2.[Id] t2Id, t1.[Type], t2.[Type] t2Type, ( CASE WHEN t2.[Type] IS NULL THEN 0 WHEN t2.[Type] = t1.[Type] THEN 1 ELSE 0 END ) AS ShouldCompareWithPrevious, t1.[Begin] CurrBegin, t1.[End] CurrEnd, t2.[Begin] PrevBegin, t2.[End] PrevEnd FROM @MyTable t1 LEFT OUTER JOIN @MyTable t2 ON t1.Id = t2.Id + 1 ) intermideate