查询相接数据

查询相连数据
想要得到以下结果
如果是连续的数据比如1,2,3,4,5 那就是1-5显示,如果不是连续的比如12,那就显示为12 ,比如17,18,19,20又是连续的,那就显示为17-20  实例: create table T(ID int)  select '1' union all
 select '2' union all 
 select '3' union all
 select '4' union all
 select '5' union all
 select '12' union all
 select '17' union all
 select '18' union all
 select '19' union all
 select '20' union all
 select '25' union all 
查询相接数据
------解决方案--------------------
第一次尝试sql server 2000以上的功能,可能不是最好的
;with cte as 
(
select ID as col1, ID as col2 from T a where not exists(select 1 from T where ID=a.ID-1)
union all
    select b.col1, a.ID from T a inner join cte b on a.ID=b.col2+1
 )
select str(a.ID)+case when b.col2>a.ID then '-'+str(col2) else '' end 
from T a cross apply (select max(col2) as col2 from cte where col1=a.ID) b
where not exists(select 1 from T where ID=a.ID-1)

------解决方案--------------------
这个没有空格
;with cte as 
(
select ID as col1, ID as col2 from T a where not exists(select 1 from T where ID=a.ID-1)
union all
    select b.col1, a.ID from T a inner join cte b on a.ID=b.col2+1
 )
select ltrim(a.ID)+case when b.col2>a.ID then '-'+ltrim(col2) else '' end 
from T a cross apply (select max(col2) as col2 from cte where col1=a.ID) b
where not exists(select 1 from T where ID=a.ID-1)

------解决方案--------------------
还有
 ;with t1 as 
(
    select ROW_NUMBER() over(order by ID) n, ID
    from T a
    where not exists(select 1 from T where ID=a.ID-1)
 ),
 t2 as
 (
    select ROW_NUMBER() over(order by ID) n, ID
    from T a
    where not exists(select 1 from T where ID=a.ID+1)
 )
select ltrim(t1.ID)+case when t2.ID>t1.ID then '-'+ltrim(t2.ID) else '' end 
from t1 join t2 on t1.n=t2.n

------解决方案--------------------
引用:
还有
 ;with t1 as 
(
    select ROW_NUMBER() over(order by ID) n, ID
    from T a
    where not exists(select 1 from T where ID=a.ID-1)
 ),
 t2 as
 (
    select ROW_NUMBER() over(order by ID) n, ID
    from T a
    where not exists(select 1 from T where ID=a.ID+1)
 )
select ltrim(t1.ID)+case when t2.ID>t1.ID then '-'+ltrim(t2.ID) else '' end 
from t1 join t2 on t1.n=t2.n
赞一个!