码迷,mamicode.com
首页 > 其他好文 > 详细

第30章 分析函数

时间:2018-08-04 18:48:44      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:ott   tno   order by   style   ada   row   sql   不用   tween   

第30章 分析函数
select ename,sal,(select max(sal) from emp) msal from emp;
select ename,sal,max(sal) over() msal from emp;
求每个部门的最大值
select ename,sal,max(sal) over(partition by deptno) msal from emp;

统计函数中一般不用加上with 子函数,效率并没得到提高

薪水递归求和
select ename,sal,sum(sal) over(order by deptno rows between unbounded preceding and current row) tsal from emp;
SQL> select ename,sal,sum(sal) over(order by deptno rows between unbounded preceding and current row) tsal from emp;

ENAME SAL TSAL
---------- ---------- ----------
CLARK 2450 2450
KING 5000 7450
MILLER 1300 8750
JONES 2975 11725
FORD 3000 14725
ADAMS 1100 15825
SMITH 800 16625
SCOTT 3000 19625
WARD 1250 20875
TURNER 1500 22375
ALLEN 1600 23975

ENAME SAL TSAL
---------- ---------- ----------
JAMES 950 24925
BLAKE 2850 27775
MARTIN 1250 29025

14 rows selected.


统计名次row_number()
select ename,sal,row_number() over(order by sal desc) top from emp;


查询每个部门的薪水前三名
select ename,deptno,sal from (select ename,deptno,sal,row_number() over(partition by deptno order by sal desc) top from emp) where top<=3;

SQL> select ename,deptno,sal from (select ename,deptno,sal,row_number() over(partition by deptno order by sal desc) top from emp) where top<=3;

ENAME DEPTNO SAL
---------- ---------- ----------
KING 10 5000
CLARK 10 2450
MILLER 10 1300
SCOTT 20 3000
FORD 20 3000
JONES 20 2975
BLAKE 30 2850
ALLEN 30 1600
TURNER 30 1500

9 rows selected.

如果工资相等算作并列第几名第几名
select ename,deptno,sal from (select ename,deptno,sal,dense_rank() over(partition by deptno order by sal desc) top from emp) where top<=3;

SQL> select ename,deptno,sal from (select ename,deptno,sal,dense_rank() over(partition by deptno order by sal desc) top from emp) where top<=3;

ENAME DEPTNO SAL
---------- ---------- ----------
KING 10 5000
CLARK 10 2450
MILLER 10 1300
SCOTT 20 3000
FORD 20 3000
JONES 20 2975
ADAMS 20 1100
BLAKE 30 2850
ALLEN 30 1600
TURNER 30 1500

10 rows selected.

 

第30章 分析函数

标签:ott   tno   order by   style   ada   row   sql   不用   tween   

原文地址:https://www.cnblogs.com/tudousix/p/9419211.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!