日期:2014-05-18  浏览次数:20507 次

求助 急 马上结贴
表结构   如下
CREATE   TABLE   [hbts]   (
[startIP]   [bigint]   NOT   NULL   ,
[endip]   [bigint]   NOT   NULL   ,
[pos]   [nvarchar]   (255)   COLLATE   Chinese_PRC_CI_AS   NULL   ,
)   ON   [PRIMARY]
GO

需要得到结果  

把pos中相同的  
startip     和   endip   连续的   合并为一条记录
比如
源数据
0,       10       河北
123,456,河北
457,789,河北
结果
0,10   河北
123,789   河北




------解决方案--------------------
请参阅这个:


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 * 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

我希望找出所有可以合并的连续区间,并尽可能合并为最大的区间


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 行)


------解决方案--------------------
--参考
create table test
(
[min] int,
[max] int
)

insert into test select 1, 5
insert into test select 6, 10
insert into test select 11, 15
insert into test select 20, 30
insert into test select 40, 50
insert into test select 51, 60


--语句
select [min],[max] = (select min([max]) from test t1
where [max]> t2.[min] and not exists(select 1 from test where [min] = t1.[max]+1)
)
from test t2
where not exists(select 1 from test where [max] = t2.[min]-1)

--结果
1 15
20 30
40 60