create table 金額(
key1 char(1),
key2 char(2),
money number(3));
insert into 金額 values('A','A1', 10);
insert into 金額 values('A','A1', 20);
insert into 金額 values('A','A1', 30);
insert into 金額 values('A','A2',120);
insert into 金額 values('B','B1', 50);
insert into 金額 values('B','B1', 60);
insert into 金額 values('B','B1', 70);
insert into 金額 values('B','B2', 10);
insert into 金額 values('B','B2', 30);
insert into 金額 values('B','B3', 70);
insert into 金額 values('C','C1', 20);
insert into 金額 values('C','C2', 20);
insert into 金額 values('C','C3', 20);
insert into 金額 values('C','C4', 10);
insert into 金額 values('C','C5', 0);
commit;
--■■■分析関数を使う方法■■■
select key1,key2,money
from (select key1,key2,sum(money) as money,
dense_rank() over(partition by key1 order by sum(money) desc) as Rank
from 金額
group by key1,key2)
where Rank <= 2
order by key1,Rank,key2;
--■■■相関サブクエリを使う方法■■■
select key1,key2,sum(money) as money
from 金額 a
group by key1,key2
having (select count(distinct sum(b.money))+1
from 金額 b
where b.key1=a.key1
group by b.key2
having sum(b.money) > sum(a.money)) <= 2
order by key1,money desc,key2;