以下是我的数据:
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
我尝试输出以下结果:
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是一个整数,而不是varchar。我想要使用相同的键(FirstKey,SecondKey)来跟随彼此的序列出现在同一行上。我的结果是由FirstKey,SecondKey,Sequence订购的 有没有人知道在SQL中输出它的解决方案(我使用Sybase 12.5运行)
答案 0 :(得分:2)
一个常见的解决方案是使用ROW_NUMBER以及序列中存在间隙的事实:
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