1. 행열변환
SELECT SUM(CASE WHEN MM=1 THEN CNT ELSE 0 END) M1
, SUM(CASE WHEN MM=2 THEN CNT ELSE 0 END) M2
, SUM(CASE WHEN MM=3 THEN CNT ELSE 0 END) M3
, SUM(CASE WHEN MM=4 THEN CNT ELSE 0 END) M4
, SUM(CASE WHEN MM=5 THEN CNT ELSE 0 END) M5
, SUM(CASE WHEN MM=6 THEN CNT ELSE 0 END) M6
, SUM(CASE WHEN MM=7 THEN CNT ELSE 0 END) M7
, SUM(CASE WHEN MM=8 THEN CNT ELSE 0 END) M8
, SUM(CASE WHEN MM=9 THEN CNT ELSE 0 END) M9
, SUM(CASE WHEN MM=10 THEN CNT ELSE 0 END) M10
, SUM(CASE WHEN MM=11 THEN CNT ELSE 0 END) M11
, SUM(CASE WHEN MM=12 THEN CNT ELSE 0 END) M12
FROM (SELECT MONTH(HIRE_DATE) AS MM
, COUNT(*) AS CNT
FROM EMPLOYEES
WHERE YEAR(HIRE_DATE)=1999
GROUP BY MONTH(HIRE_DATE)
) DS
2. 행열변환 응용1
SELECT YR
, SUM(CASE WHEN MM=1 THEN CNT ELSE 0 END) M1
, SUM(CASE WHEN MM=2 THEN CNT ELSE 0 END) M2
, SUM(CASE WHEN MM=3 THEN CNT ELSE 0 END) M3
, SUM(CASE WHEN MM=4 THEN CNT ELSE 0 END) M4
, SUM(CASE WHEN MM=5 THEN CNT ELSE 0 END) M5
, SUM(CASE WHEN MM=6 THEN CNT ELSE 0 END) M6
, SUM(CASE WHEN MM=7 THEN CNT ELSE 0 END) M7
, SUM(CASE WHEN MM=8 THEN CNT ELSE 0 END) M8
, SUM(CASE WHEN MM=9 THEN CNT ELSE 0 END) M9
, SUM(CASE WHEN MM=10 THEN CNT ELSE 0 END) M10
, SUM(CASE WHEN MM=11 THEN CNT ELSE 0 END) M11
, SUM(CASE WHEN MM=12 THEN CNT ELSE 0 END) M12
FROM (SELECT YEAR(HIRE_DATE) AS YR
, MONTH(HIRE_DATE) AS MM
, COUNT(*) AS CNT
FROM EMPLOYEES
WHERE YEAR(HIRE_DATE) IN ('1998', '1999')
GROUP BY YEAR(HIRE_DATE), MONTH(HIRE_DATE)
) DS
GROUP BY YR
'Dev. Database' 카테고리의 다른 글
행열 변환2 (가로 -> 세로) (0) | 2019.05.08 |
---|---|
[분석함수] RANK(), DENSE_RANK() (0) | 2019.05.02 |
WITH 절 - 서브쿼리 중복 사용 방지 (0) | 2019.05.02 |
복잡한 쿼리 효율적으로 작성하기 (0) | 2019.04.25 |
Mybatis에서 alias의 중요성 (0) | 2017.11.16 |