列变区间问题

有一个表 
num 
001
002
003
004
007
008
009
想让他们变成区间形式 
a    b
001  004
007  009
如何才能办到,我需要的是一条sql语句
------------------------------------
--构建数据
declare @tb table(num varchar(10))
insert into @tb select '001'
insert into @tb select '002'
insert into @tb select '003'
insert into @tb select '004'
insert into @tb select '007'
insert into @tb select '008'
insert into @tb select '009'
--SQL 2000
--方法1
select
    a.num as [a],min(b.num) as [b]
from
    (select * from @tb t where not exists(select 1 from @tb where num=t.num-1)) a,
    (select * from @tb t where not exists(select 1 from @tb where num=t.num+1)) b
where
    a.num<=b.num
group by
    a.num
--方法2
select a=min(num),b=max(num) from 
(select px=(select count(1) from @tb where num<=a.num),num from @tb a) b
group by cast(num as int)-px
--SQL 2005
select min(num) as a,max(num) as b from
(
    select px = row_number() over(order by num),*
    from @tb
)T
group by cast(num as int)-px
--第一种方法比较绕。
--后两种方法思路很简单,就是按cast(num as int)-px分组,然后取最小值和最大值。
--以上3种方法都能得到如下结果:
/*
a          b         
---------- ----------
001        004
007        009
(所影响的行数为 2 行)
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值