Truly Wacky! What the heck are you using this for? Anyway, I THINK this will do it:set nocount onDeclare @tb Table ([id] int, [min] int, [max] int)insert @tbSelect 10, 400, 500 UNION ALLSElect 20, 350, 470 UNION ALL Select 30, 480, 520 UNION ALLSelect 40, 460, 540 UNION ALLSelect 50, 310, 360 Select base = bg.[id] ,a.[id] ,[min] = case when a.[min] < bg.[min] then bg.[min] else a.[min] end ,[max] = case when a.[max] < bg.[max] then a.[max] else bg.[max] endFrom --Get the background record (SElect [id], [min], [max] from @tb where [id] = (Select min([id]) from @tb)) bgJOIN @tb a --limit results to ranges that overlap the background ON bg.[min] <= a.[max] AND bg.[max] >= a.[min]Left JOIN (--Get all previous records that are completely obsured by current record Select y.[id] From @tb z JOIN @tb y ON --only previous records y.[id] < z.[id] AND --only records completely obscured y.[min] >= z.[min] AND y.[max] <= z.[max] ) as obscured ON a.[id] = obscured.[id]--exclude the background record from resultsWhere a.[id] <> bg.[id]--exlcude previous completely obscured recordsAND obscured.[id] is NULL
Be One with the OptimizerTG