declare @t table(ID int,[Begin] int,[End] int)
insert into @t select 1,1,3
insert into @t select 2,4,5
insert into @t select 3,6,8
insert into @t select 4,11,13
insert into @t select 5,15,18
insert into @t select 6,19,22
insert into @t select 7,23,33
insert into @t select 8,34,52select * from @t
[Begin]表示数字起点,[End]表示数字的终点第一条数据1,3表示1-3之间的数
第二条数据4,5表示4-5之间的数
第三条数据6,8表示6-8之间的数
第四条数据11,13表示11-13之间的数每条的数据[Begin]、[End]都比前一条数据的[Begin]、[End]要大因为1-3、4-5、6-8是连续的,可以合并为1-8我希望找出所有可以合并的连续区间,并尽可能合并为最大的区间

解决方案 »

  1.   

    declare @t table(ID int,[Begin] int,[End] int)
    insert into @t select 1,1,3
    insert into @t select 2,4,5
    insert into @t select 3,6,8
    insert into @t select 4,11,13
    insert into @t select 5,15,18
    insert into @t select 6,19,22
    insert into @t select 7,23,33
    insert into @t select 8,34,52--语句
    select [begin],[end] = (select min([end]) from @t t1
    where [end]>t2.[begin] and not exists(select 1 from @t where [begin] = t1.[end]+1)
    )
    from @t t2
    where not exists(select 1 from @t where [end] = t2.[begin]-1)--结果
    begin       end         
    ----------- ----------- 
    1           8
    11          13
    15          52(所影响的行数为 3 行)
      

  2.   

    To coolingpipe(冷箫轻笛)实在有些难理解其中的意思:)