问题描述
我有下表
create table Launches (Id int,Name char)
insert into Launches values
(1,'A'),(2,(3,'B'),(4,(5,(6,(7,'C'),(8,(9,'B')
结果应该是
4 - B
从 3 到 6
类似问题-
Count Number of Consecutive Occurrence of values in Table
解决方法
您可以为每个 name
减去一个枚举值,以获得相同的相邻值的常量。剩下的就是聚合:
select top (1) name,count(*),min(id),max(id)
from (select l.*,row_number() over (partition by name order by id) as seqnum
from #Launches l
) l
group by (id - seqnum),name
order by count(*) desc;
Here 是一个 dbfiddle。