[SQL] ROLLUP ν•¨μˆ˜


πŸ‘Š μ†Œκ·Έλ£Ή κ°„μ˜ μ†Œκ³„(SUBTOTAL)와 합계(GRAND TOTAL)λ₯Ό κ³„μ‚°ν•˜λŠ” ROLLUP ν•¨μˆ˜μ— λŒ€ν•΄ μ•Œμ•„λ³΄μž πŸ‘Š


β–Ά DEPT

β–Ά EMP



GROUP BY 절 μ‚¬μš©



SELECT 
    B.DNAME,
    A.JOB,
    COUNT(*) AS EMP_CNT,
    SUM(A.SAL) AS SAL_SUM
FROM EMP A,
    DEPT B
WHERE B.DEPTNO = A.DEPTNO
GROUP BY B.DNAME, A.JOB;


μ‹€ν–‰κ²°κ³Ό )



GROUP BY 절 + ORDER BY 절



SELECT 
    B.DNAME,
    A.JOB,
    COUNT(*) AS EMP_CNT,
    SUM(A.SAL) AS SAL_SUM
FROM EMP A,
    DEPT B
WHERE B.DEPTNO = A.DEPTNO
GROUP BY B.DNAME, A.JOB
ORDER BY B.DNAME, A.JOB;


μ‹€ν–‰κ²°κ³Ό )



ROLLUP ν•¨μˆ˜



SELECT 
    B.DNAME,
    A.JOB,
    COUNT(*) AS EMP_CNT,
    SUM(A.SAL) AS SAL_SUM
FROM EMP A,
    DEPT B
WHERE B.DEPTNO = A.DEPTNO
GROUP BY ROLLUP (B.DNAME, A.JOB);


μ‹€ν–‰κ²°κ³Ό )

GROUP BY μˆ˜ν–‰ μ‹œ μƒμ„±λ˜λŠ” ν‘œμ€€ 집계 9건 이외에 DNAME 별 λͺ¨λ“  JOB의 합계 3건과 λͺ¨λ“  ν–‰μ˜ ν•© 1건이 μΆ”κ°€λœ 것을 λ³Ό 수 μžˆλ‹€.



ROLLUP ν•¨μˆ˜ + ORDER BY 절



SELECT 
    B.DNAME,
    A.JOB,
    COUNT(*) AS EMP_CNT,
    SUM(A.SAL) AS SAL_SUM
FROM EMP A,
    DEPT B
WHERE B.DEPTNO = A.DEPTNO
GROUP BY ROLLUP (B.DNAME, A.JOB)
ORDER BY B.DNAME, A.JOB;


μ‹€ν–‰κ²°κ³Ό )



WITH ROLLUP



πŸ’₯ MySQLμ—μ„œλŠ” WITH ROLLUP을 μ‚¬μš© πŸ’₯

SELECT
    B.DNAME,
    A.JOB,
    COUNT(*) AS EMP_CNT,
    SUM(A.SAL) AS SAL_SUM
FROM EMP A,
    DEPT B
WHERE B.DEPTNO = A.DEPTNO
GROUP BY B.DNAME, A.JOB WITH ROLLUP;


μ‹€ν–‰κ²°κ³Ό )

Categories:

SQL