create table 売上(
Code char(1),
SubCode char(1),
Month char(6),
Amount number(2));
insert into 売上 values('A','1','200503',10);
insert into 売上 values('A','1','200504',10);
insert into 売上 values('A','2','200503',15);
insert into 売上 values('A','2','200504',15);
insert into 売上 values('B','1','200503',10);
insert into 売上 values('B','1','200504',15);
insert into 売上 values('B','2','200504',15);
insert into 売上 values('C','1','200503',30);
insert into 売上 values('C','1','200504',30);
insert into 売上 values('D','1','200504',30);
insert into 売上 values('D','2','200504',40);
commit;
select decode(grouping(Code),1,'総合計',Code) as Code,
case when 1 = all(grouping(Code),grouping(SubCode)) then null
when grouping(SubCode) = 1 then '小計'
else SubCode end as SubCode,
sum(Amount) as Amount
from 売上
group by rollup(Code,SubCode)
order by
decode(Code,'総合計',1,0),
sum(Amount) over(partition by Code) desc,
nullif(SubCode,'小計');