如何在列中找到最大不间断间隔?
实施例
ID Result
1 1
2 2
3 3
4 4
5 5
6 6
10
11
12
答案 0 :(得分:3)
您可以使用row_number()
。以下是获取first和lsat值的简单方法:
select top (1) with ties min(id), max(id)
from (select t.*, row_number() over (order by id) as seqnum
from t
) t
group by (id - seqnum)
order by count(*) desc;
要获取实际的原始行,需要另一级窗口函数:
select top (1) with ties
from (select t.*, count(*) over (partition by id - seqnum) as cnt
from (select t.*, row_number() over (order by id) as seqnum
from t
) t
) t
order by cnt desc, id;