XXXテーブル ID1 ID2 Value --- --- ----- 1 1 10 1 3 11 1 3 12 2 1 12 2 2 14 2 2 12 2 2 11 3 1 11 3 2 10 4 3 13 ID1ごとに、 ID2の最大値と、ID2が最大値の行のValueの合計を出力する 出力結果 ID1 ID2 Value --- --- ----- 1 3 23 2 2 37 3 2 10 4 3 13
select ID1, max(ID2) as ID2, sum(Value) keep(dense_rank Last order by ID2) as Value from (select 1 as ID1,1 as ID2,10 as Value from dual union select 1,3,11 from dual union select 1,3,12 from dual union select 2,1,12 from dual union select 2,2,14 from dual union select 2,2,12 from dual union select 2,2,11 from dual union select 3,1,11 from dual union select 3,2,10 from dual union select 4,3,13 from dual) group by ID1 order by ID1;
dense_rank Lastを指定して、 最大値の行の合計を取得してます