2009. 4. 24. 10:20
개발/Oracle
일단 유용한 분석함수를 보면
select scott.emp.*
, row_number() over (partition by deptno order by empno ) num
, rank() over (partition by deptno order by empno ) rank
, dense_rank() over (partition by deptno order by empno ) dense_rank
, lead(sal) over (partition by deptno order by empno ) next
, lag(sal) over (partition by deptno order by empno ) before
, sum(sal) over (partition by deptno order by empno ) sum
from scott.emp
******************************************************************************************
요걸 응용해서
세로로 되어 있는 자료를 가로로 바꿔주는 sql을 보자..
SELECT 품목
, MAX((CASE WHEN RK = 1 THEN 거래처 END)) AS "1등거래처"
, MAX((CASE WHEN RK = 1 THEN 수량 END)) AS "1등수량"
, MAX((CASE WHEN RK = 2 THEN 거래처 END)) AS "2등거래처"
, MAX((CASE WHEN RK = 2 THEN 수량 END)) AS "2등수량"
, MAX((CASE WHEN RK = 3 THEN 거래처 END)) AS "3등거래처"
, MAX((CASE WHEN RK = 3 THEN 수량 END)) AS "3등수량"
FROM (SELECT A.*
, ROW_NUMBER() OVER (PARTITION BY 품목 ORDER BY 수량 DESC) AS RK
FROM 테이블명 A
) A
WHERE RK <= 3
GROUP BY 품목
, MAX((CASE WHEN RK = 1 THEN 거래처 END)) AS "1등거래처"
, MAX((CASE WHEN RK = 1 THEN 수량 END)) AS "1등수량"
, MAX((CASE WHEN RK = 2 THEN 거래처 END)) AS "2등거래처"
, MAX((CASE WHEN RK = 2 THEN 수량 END)) AS "2등수량"
, MAX((CASE WHEN RK = 3 THEN 거래처 END)) AS "3등거래처"
, MAX((CASE WHEN RK = 3 THEN 수량 END)) AS "3등수량"
FROM (SELECT A.*
, ROW_NUMBER() OVER (PARTITION BY 품목 ORDER BY 수량 DESC) AS RK
FROM 테이블명 A
) A
WHERE RK <= 3
GROUP BY 품목
품목 1등거래처 1등수량 2등거래처 2등수량 3등업체 3등수량
이렇게 나오게 된다..