본문
ROLLUP 합계, 소계 구하기 (GROUP BY)
오라클 GROUP BY 쿼리에서 ROLLUP 함수를 사용하여 손쉽게 합계와 소계를 구할 수 있다.
테스트에 앞서 테스트용 가상 테이블, 데이터 생성를 생성한다.
WITH TEST_TABLE AS (
SELECT 'SMITH' NM, 'CLERK' JOB, 800 SAL, 'RESEARCH' DEPT FROM DUAL UNION ALL
SELECT 'ALLEN' NM, 'SALESMAN' JOB, 1600 SAL, 'SALES' DEPT FROM DUAL UNION ALL
SELECT 'WARD' NM, 'SALESMAN' JOB, 1250 SAL, 'SALES' DEPT FROM DUAL UNION ALL
SELECT 'JONES' NM, 'MANAGER' JOB, 2975 SAL, 'RESEARCH' DEPT FROM DUAL UNION ALL
SELECT 'MARTIN' NM, 'SALESMAN' JOB, 1250 SAL, 'SALES' DEPT FROM DUAL UNION ALL
SELECT 'BLAKE' NM, 'MANAGER' JOB, 2850 SAL, 'SALES' DEPT FROM DUAL UNION ALL
SELECT 'CLARK' NM, 'MANAGER' JOB, 2450 SAL, 'ACCOUNTING' DEPT FROM DUAL UNION ALL
SELECT 'SCOTT' NM, 'ANALYST' JOB, 3000 SAL, 'RESEARCH' DEPT FROM DUAL UNION ALL
SELECT 'KING' NM, 'PRESIDENT' JOB, 5000 SAL, 'ACCOUNTING' DEPT FROM DUAL UNION ALL
SELECT 'TURNER' NM, 'SALESMAN' JOB, 1500 SAL, 'SALES' DEPT FROM DUAL UNION ALL
SELECT 'ADAMS' NM, 'CLERK' JOB, 1100 SAL, 'RESEARCH' DEPT FROM DUAL UNION ALL
SELECT 'JAMES' NM, 'CLERK' JOB, 950 SAL, 'SALES' DEPT FROM DUAL UNION ALL
SELECT 'FORD' NM, 'ANALYST' JOB, 3000 SAL, 'RESEARCH' DEPT FROM DUAL UNION ALL
SELECT 'MILLER' NM, 'CLERK' JOB, 1300 SAL, 'ACCOUNTING' DEPT FROM DUAL
)
1. GROUP BY 컬럼이 하나인 경우
SELECT JOB, SUM(SAL)
FROM TEST_TABLE
GROUP BY ROLLUP(JOB);
2. GROUP BY 컬럼이 두 개 이상인 경우
합계,소계가 계산되어 표시된다.
SELECT JOB, DEPT, SUM(SAL)
FROM TEST_TABLE
GROUP BY ROLLUP(JOB, DEPT);
3. GROUP BY 컬럼이 두 개 이상 - 합계만 표시
HAVING 절에 GROUPING_ID 함수를 이용하여 소계 값을 제외할 수 있다.
SELECT JOB, DEPT, SUM(SAL)
FROM TEST_TABLE
GROUP BY ROLLUP(JOB, DEPT) HAVING GROUPING_ID(JOB, DEPT) IN (0, 3);
4. ROLLUP 컬럼에 합계 표시
DECODE 함수를 이용하여 합계 컬럼 값을 NULL 대신 합계로 표시할 수 있다.
SELECT DECODE(JOB, NULL, '합계', JOB) JOB, DEPT, SUM(SAL)
FROM TEST_TABLE
GROUP BY ROLLUP(JOB, DEPT) HAVING GROUPING_ID(JOB, DEPT) IN (0, 3);
→ 출처: https://gent.tistory.com/57
댓글