【发布时间】:2017-04-16 10:28:20
【问题描述】:
我有一个简单的表格,其中包含分组 (GRP_ID) 中的值 (ID)。
create table tst as
select 1 grp_id, 1 id from dual union all
select 1 grp_id, 1 id from dual union all
select 1 grp_id, 2 id from dual union all
select 2 grp_id, 1 id from dual union all
select 2 grp_id, 2 id from dual union all
select 2 grp_id, 2 id from dual union all
select 3 grp_id, 3 id from dual;
使用分析函数很容易找到每个组的最大值。
select grp_id, id,
max(id) over (partition by grp_id) max_grp
from tst
order by 1,2;
GRP_ID ID MAX_GRP
---------- ---------- ----------
1 1 2
1 1 2
1 2 2
2 1 2
2 2 2
2 2 2
3 3 3
但目标是找到不包括当前行的值的最大值。
这是预期的结果(MAX_OTHER_ID 列):
GRP_ID ID MAX_GRP MAX_OTHER_ID
---------- ---------- ---------- ------------
1 1 2 2
1 1 2 2
1 2 2 1
2 1 2 2
2 2 2 2
2 2 2 2
3 3 3
请注意,在 GRP_ID = 2 中存在与 MAX 值的关系,因此 MAX_OTHER_ID 保持不变。
我确实管理了这两个步骤的解决方案,但我想知道是否有更直接和简单的解决方案。
with max1 as (
select grp_id, id,
row_number() over (partition by grp_id order by id desc) rn
from tst
)
select GRP_ID, ID,
case when rn = 1 /* MAX row per group */ then
max(decode(rn,1,to_number(null),id)) over (partition by grp_id)
else
max(id) over (partition by grp_id)
end as max_other_id
from max1
order by 1,2
;
【问题讨论】: