我有一个有两列整数的表。第一列代表开始索引,第二列代表结束索引。 + u. V9 N3 r- b R: jSTART END1 89 1314 2020 2530 4242 4960 67到目前为止,这很简单。我想做的是将随后的所有记录分成一组: 6 S( X0 j) D0 h4 V4 Q' lSTART END 2530 4960 记录可以与上一个结束索引相同,也可以从1的边距开始:6 @4 @! w1 E* z; F+ G
START END1 1010 2000 和2 U2 Z7 Z& m* _$ t/ p
START END1 1011 都会导致) o) r- ` T* G& e3 J) o1 a
START END1 20我正在使用SQL Server 2008 R2。% r! a [( @4 T% E- ?# P7 M4 K
任何帮助都会很棒6 X" z. V- [+ A' G3 ]( v$ j
0 q, ]' ?! J2 v% c解决方案: # A* J# F' F( s! m& Y 这个例子适用于你,请让我知道它是否不适用于其他数据+ W+ l0 z, r+ W/ t
create table #Range ( [Start] INT, [End] INT)insert into #Range ([Start],[End]) Values (1,8)insert into #Range ([Start],[End]) Values (9,13)insert into #Range ([Start],[End]) Values (14,20)insert into #Range ([Start],[End]) Values (20,25)insert into #Range ([Start],[End]) Values (30,42)insert into #Range ([Start],[End]) Values (42,49)insert into #Range ([Start],[End]) Values (60,67);with RangeTable as(select t1.[Start], t1.[End], row_number() over (order by t1.[Start]) as [Index]from #Range t1where t1.Start not in (select [End] from #Range Union select [End] from #Range select t1.[Start], case when t2.[Start] is null then (select max([End]) from #Range) else (select max([End]) from #Range where t2.[Start] > [End])end as [End] from RangeTable t1left join RangeTable t2on t1.[Index] = t2.[Index]-1drop table #Range;