Group consecutive rows that are incremented by 1

时光总嘲笑我的痴心妄想 提交于 2020-01-16 04:10:10

问题


Here are my datas :

FirstKey   SecondKey    Sequence
A1         B1           10001
A1         B1           10002
A1         B1           10003
A1         B1           10004
A1         B2           10001
A1         B2           10003
A1         B2           10005
A1         B3           10001
A1         B3           10002
A1         B3           10003
A2         B4           20001
A2         B5           20002
A2         B5           20003
A2         B6           20004

I try to output the following result:

FirstKey   SecondKey    StartSequence EndSequence
A1         B1           10001         10004
A1         B2           10001         10001
A1         B2           10003         10003
A1         B2           10005         10005
A1         B3           10001         10003
A2         B4           20001         20001
A2         B5           20002         20003
A2         B6           20004         20004

Sequence is an integer, not a varchar. I want sequences that follow each other with the same key (FirstKey, SecondKey) to appear on the same row. My result is ordered by FirstKey, SecondKey, Sequence Does anyone know a solution to output this in SQL (I'm running with Sybase 12.5)


回答1:


A common solution utilizes a ROW_NUMBER and the fact that there are gaps in your sequence:

select FirstKey,
   SecondKey,
   min(Sequence),
   max(Sequence)
from 
 (
   select FirstKey,
      SecondKey,
      Sequence,
      -- meaningless value, but the same for sequential rows
      Sequence -
      row_number() over (partition by FirstKey, SecondKey order by Sequence) as grp 
   from tab
 ) dt
group by 
   FirstKey,
   SecondKey,
   grp


来源:https://stackoverflow.com/questions/32991863/group-consecutive-rows-that-are-incremented-by-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!