首页 > 解决方案 > 需要在 SQL 中对值进行分组

问题描述

下面是我的表数据结构。

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

数据

谢谢,名利

标签: sqloraclewindow-functionsgaps-and-islands

解决方案


这读作是一个间隙和孤岛问题,您希望将具有相同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

DB Fiddle 上的演示

身份证 | FROM_SRNO | MAX_SRNO | AMT
--: | --------: | --------: | ---:
100 | 1 | 1 | 0
100 | 2 | 3 | 1000
100 | 4 | 4 | 0
100 | 5 | 5 | 2000

推荐阅读