강좌를 참고해서 만들어보았습니다.. 잘못된 점이 있다면 알려주세요.
with t as (
select 'A' flag, 'AAA' category, 'A1' name, NULL range, 10 cnt, 2 code1, 0 code2 from dual
union all select 'A', 'BBB', 'A2', NULL , 2, 1, 1 from dual
union all select 'B', 'CCC', 'B1', '1-2', 3, 0, 0 from dual
union all select 'B', 'CCC', 'B1', '2-3', 1, 1, 0 from dual
union all select 'B', 'CCC', 'B2', '3-4', 2, 0, 0 from dual
union all select 'B', 'CCC', 'B3', '4-5', 1, 0, 0 from dual
union all select 'C', 'DDD', 'C1', '1-2', 4, 0, 2 from dual
union all select 'C', 'DDD', 'C1', '2-3', 1, 1, 1 from dual
union all select 'C', 'DDD', 'C2', '3-4', 1, 1, 0 from dual
)
select case when flag is null then '합계'
when flag='A' and grouping(category)=1 and grouping(name)=1 and grouping(range)=1 then '소계1'
when flag='B' and grouping(category)=1 and grouping(name)=1 and grouping(range)=1 then '소계2'
when flag='C' and grouping(category)=1 and grouping(name)=1 and grouping(range)=1 then '소계3'
else flag
end flag,
category,
name,
range,
sum(cnt),
sum(code1),
sum(code2)
from t
group by rollup (flag, (category,name, range))
WITH t AS ( SELECT 'A' flag, 'AAA' category, 'A1' name, NULL range, 10 cnt, 2 code1, 0 code2 FROM dual UNION ALL SELECT 'A', 'BBB', 'A2', NULL , 2, 1, 1 FROM dual UNION ALL SELECT 'B', 'CCC', 'B1', '1-2', 3, 0, 0 FROM dual UNION ALL SELECT 'B', 'CCC', 'B1', '2-3', 1, 1, 0 FROM dual UNION ALL SELECT 'B', 'CCC', 'B2', '3-4', 2, 0, 0 FROM dual UNION ALL SELECT 'B', 'CCC', 'B3', '4-5', 1, 0, 0 FROM dual UNION ALL SELECT 'C', 'DDD', 'C1', '1-2', 4, 0, 2 FROM dual UNION ALL SELECT 'C', 'DDD', 'C1', '2-3', 1, 1, 1 FROM dual UNION ALL SELECT 'C', 'DDD', 'C2', '3-4', 1, 1, 0 FROM dual ) SELECT NVL(flag, '전체') flag , DECODE(GROUPING_ID(flag, name), 3, '합계', 1, '소계', 0, category) category , name , range , SUM(cnt) cnt , SUM(code1) code1 , SUM(code2) code2 FROM t GROUP BY ROLLUP(flag, (category, name, range)) ;