作者cutekid (可爱小孩子)
看板Database
标题[SQL ]取得每段连续数字的开始与结束(分享做法)
时间Wed Sep 6 15:56:13 2017
Hello,
工作刚好遇到一个问题:
table 里有个栏位: ID(型态 int)
里面可能有多段连续数字(如下例子)
如何取得它们「起点」与「终点」
例子:
ID
--
1
2
3
5
6
8
9
10
希望得到:
Begin | End
-----------
1 | 3
5 | 6
8 | 10
解法(MSSQL):
;with tb1 as (
select ID,row_number() over (order by ID) as num
from table
)
select distinct min(t2.ID) as Begin,max(t2.ID) as End
from tb1 t1 inner join tb1 t2
on t2.ID - t1.ID = t2.num - t1.num
group by t1.ID
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 61.221.80.36
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Database/M.1504684576.A.4C9.html
1F:→ zenixls2: 这样做table大一点就爆炸了吧,不如用not exist挑各自边 09/06 17:07
2F:→ zenixls2: 界出来 09/06 17:07