[面试集锦] SQL列折行查找
请用一条sql语句查询出scott.emp表中每个部门工资前三位的数据,显示结果如下:
DEPTNO SAL1 SAL2 SAL3
-------- -------- -------- ---------
10 5000 2450 1300
20 3000 2975 1100
30 2850 1600 1500
最常见的解法如下:
SELECT
DEPTNO, MAX(SAL) SAL1, MAX(DECODE( T ,2 ,SAL)) SAL2,
MIN(SAL) SAL3
FROM( SELECT SAL, DEPTNO, T
FROM( SELECT EMPNO, ENAME, SAL,
ROW_NUMBER() OVER(PARTITION BY DEPTNO ORDER BY SAL DESC) T, DEPTNO
FROM EMP) E
WHERE E.T <= 3)
GROUP BY DEPTNO