组关闭号
问题描述:
我有一个包含2列整数的表.第一列代表开始索引,第二列代表结束索引.
I have a table with 2 columns of integers. The first column represents start index and the second column represents end index.
START END
1 8
9 13
14 20
20 25
30 42
42 49
60 67
简单到目前为止.我想将所有跟随的记录分组:
Simple So far. What I would like to do is group all the records that follow together:
START END
1 25
30 49
60 67
记录可以跟在与上一个结束索引相同的索引处开始,或者以1的边距开始.
A record can follow by Starting on the same index as the previous end index or by a margin of 1:
START END
1 10
10 20
和
START END
1 10
11 20
都将导致
START END
1 20
我正在使用SQL Server 2008 R2.
I'm using SQL Server 2008 R2.
任何帮助都是伟大的
答
这适用于您的示例,请告诉我它是否不适用于其他数据
This works for your example, let me know if it doesn't work for other data
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 t1
where t1.Start not in (select
[End]
from
#Range
Union
select
[End] + 1
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 t1
left join
RangeTable t2
on
t1.[Index] = t2.[Index]-1
drop table #Range;