需要在SQL中对值进行分组
下面是我的表数据结构需要在SQL中对值进行分组,sql,oracle,window-functions,gaps-and-islands,Sql,Oracle,Window Functions,Gaps And Islands,下面是我的表数据结构 select 100 id, 1 srno,0 amt from dual union all select 100 id, 2 srno, 1000 amt from dual union all select 100 id, 3 srno, 1000 amt from dual union all select 100 id, 4 srno, 0 amt from dual union all select 1
select 100 id, 1 srno,0 amt from dual
union all
select 100 id, 2 srno, 1000 amt from dual
union all
select 100 id, 3 srno, 1000 amt from dual
union all
select 100 id, 4 srno, 0 amt from dual
union all
select 100 id, 5 srno, 2000 amt from dual
我想要这样的结果
ID From_Srno To_Srno amt
100 1 1 0
100 2 3 1000
100 4 4 0
100 5 5 2000
谢谢,
Fame这是一个间隙和孤岛问题,您希望将具有相同的
amt
的“相邻”行组合在一起
我建议使用行号之间的差异来定义组:
select id, min(srno) from_srno, max(srno) max_srno, amt
from (
select t.*,
row_number() over(partition by id order by srno) rn1,
row_number() over(partition by id, amt order by srno) rn2
from mytable t
) t
group by id, amt, rn1 - rn2
:
ID | FROM_SRNO | MAX_SRNO | AMT
--: | --------: | -------: | ---:
100 | 1 | 1 | 0
100 | 2 | 3 | 1000
100 | 4 | 4 | 0
100 | 5 | 5 | 2000
ID |来自|最大|金额
--: | --------: | -------: | ---:
100 | 1 | 1 | 0
100 | 2 | 3 | 1000
100 | 4 | 4 | 0
100 | 5 | 5 | 2000
请解释您想要实现的逻辑。这并不明显。