【问题标题】:Need to group values in SQL需要在 SQL 中对值进行分组
【发布时间】:2023-04-07 23:07:01
【问题描述】:

下面是我的表数据结构。

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

谢谢, 名气

【问题讨论】:

  • 请说明您要实现的逻辑。不明显。

标签: sql oracle window-functions gaps-and-islands


【解决方案1】:

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

Demo on DB Fiddle

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

【讨论】:

    猜你喜欢
    • 2021-03-27
    • 2020-05-23
    • 1970-01-01
    • 2023-01-04
    • 2020-02-26
    • 2013-01-27
    • 2011-04-15
    • 2018-11-27
    • 2021-12-23
    相关资源
    最近更新 更多