Oracle之over partition by分组
Oracle之over partition by分组
1、查询出部门的最低工资的雇员号 ,有位高人给出了答案如下:
[sql] SELECT MIN(SAL) OVER(PARTITION BY DEPTNO) SALARY ,DEPTNO FROM EMP
该答案确实实现了各部门的最低雇员薪资,但却没有给出具体的雇员,于是又如下:
[sql] SELECT EMPNO, ENAME, SAL,MIN(SAL) OVER(PARTITION BY DEPTNO) SALARY, DEPTNO FROM EMP EMPNO ENAME SAL SALARY DEPTNO 1 7782 CLARK 2450.00 1300 10 2 7839 KING 5000.00 1300 10 3 7934 MILLER 1300.00130010 4 7566 JONES 2975.00 800 20 5 7902 FORD 3000.00 800 20 6 7876 ADAMS 1100.00 800 20 7 7369 SMITH 800.00 800 20 8 7788 SCOTT 3000.00 800 20 9 7521 WARD 1250.00 950 30 10 7844 TURNER 1500.0095030 11 7499 ALLEN 1600.00 950 30 12 7900 JAMES 950.00 950 30 13 7698 BLAKE 2850.00 950 30 14 7654 MARTIN 1250.0095030
从结果上可以看出每一列都查询出来了,但该结果集明显不是想要的答案,所以如下:
[sql] SELECT * FROM (SELECT EMPNO,ENAME, DEPTNO, SAL, MIN(SAL) OVER(PARTITION BY DEPTNO) SALARY FROM EMP) WHERE SAL = SALARY EMPNO ENAME DEPTNO SAL SALARY 1 7934 MILLER 10 1300.00 1300 2 7369 SMITH 20 800.00 800 3 7900 JAMES 30 950.00 950 [sql] SELECT DEPTNO, ENAME, SAL, SUM(SAL) OVER(PARTITION BY DEPTNO ORDER BY ENAME) 部门连续求和, --各部门的薪水"连续"求和 SUM(SAL) OVER(PARTITION BY DEPTNO) 部门总和, -- 部门统计的总和,同一部门总和不变 100 * ROUND(SAL / SUM(SAL) OVER(PARTITION BY DEPTNO), 4) "部门份额(%)", SUM(SAL) OVER(ORDER BY DEPTNO, ENAME) 连续求和, --所有部门的薪水"连续"求和 SUM(SAL) OVER() 总和, -- 此处sum(sal) over () 等同于sum(sal),所有员工的薪水总和 100 * ROUND(SAL / SUM(SAL) OVER(), 4) "总份额(%)" FROM EMP
当使用了ORDER BY之后所求的和就是连续的了,总之记住OVER是分析,GROUP BY是分组,至于如何选择就看自己了