本文共 1043 字,大约阅读时间需要 3 分钟。
请用一条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( RN, 2, sal )) sal2, min( sal ) sal3 FROM (SELECT * FROM ( SELECT DEPTNO, SAL, ROW_NUMBER () OVER ( PARTITION BY DEPTNO ORDER BY SAL DESC ) AS RN FROM EMP ) WHERE RN <= 3 ) GROUP BY deptno
下面来分析一下这个题
1.首先将emp表按deptno进行分组,取出分组后的前3条数据
SELECT * FROM ( SELECT DEPTNO, SAL, ROW_NUMBER () OVER ( PARTITION BY DEPTNO ORDER BY SAL DESC ) AS RN FROM EMP ) WHERE RN <= 3
row_number() over()函数,用于给数据库表中的记录进行标号,在使用的时候,其后还跟着一个函数 over(),而函数 over() 的作用是将表中的记录进行分组和排序
即:ROW_NUMBER() OVER(PARTITION BY 分组的字段名 ORDER BY 排序的字段名)
2.将上面的查询作为子查询
SELECT deptno, max( sal ) sal1, max(decode( RN, 2, sal )) sal2, min( sal ) sal3 FROM (SELECT * FROM ( SELECT DEPTNO, SAL, ROW_NUMBER () OVER ( PARTITION BY DEPTNO ORDER BY SAL DESC ) AS RN FROM EMP ) WHERE RN <= 3 ) GROUP BY deptno
使用decode()函数判断字符串是否一样,DECODE(value,if1,then1,if2,then2,if3,then3,...,else)
转载地址:http://csqen.baihongyu.com/