# 傅老师课堂：Oracle高级查询之OVER (PARTITION BY ..)

select e.ename, e.job, e.sal, e.deptno
from scott.emp e,
(select e.deptno, max(e.sal) sal from scott.emp e group by e.deptno) me
where e.deptno = me.deptno
and e.sal = me.sal;

select e.ename, e.job, e.sal, e.deptno
from (select e.ename,
e.job,
e.sal,
e.deptno,
rank() over(partition by e.deptno order by e.sal desc) rank
from scott.emp e) e
where e.rank = 1;
select e.ename, e.job, e.sal, e.deptno
from (select e.ename,
e.job,
e.sal,
e.deptno,
dense_rank() over(partition by e.deptno order by e.sal desc) rank
from scott.emp e) e
where e.rank = 1;

over:  在什么条件之上。
partition by e.deptno:  按部门编号划分（分区）。
order by e.sal desc:  按工资从高到低排序（使用rank()/dense_rank() 时，必须要带order by否则非法）
rank()/dense_rank():  分级

rank():  跳跃排序，如果有两个第一级时，接下来就是第三级。
dense_rank():  连续排序，如果有两个第一级时，接下来仍然是第二级。

select e.ename,
e.job,
e.sal,
e.deptno,
e.sal - me.min_sal diff_min_sal,
me.max_sal - e.sal diff_max_sal
from scott.emp e,
(select e.deptno, min(e.sal) min_sal, max(e.sal) max_sal
from scott.emp e
group by e.deptno) me
where e.deptno = me.deptno
order by e.deptno, e.sal;

select e.ename,
e.job,
e.sal,
e.deptno,
nvl(e.sal - min(e.sal) over(partition by e.deptno), 0) diff_min_sal,
nvl(max(e.sal) over(partition by e.deptno) - e.sal, 0) diff_max_sal
from scott.emp e;

select e.ename,
e.job,
e.sal,
e.deptno,
lag(e.sal, 1, 0) over(partition by e.deptno order by e.sal) lag_sal,
nvl(lead(e.sal) over(partition by e.deptno order by e.sal) - e.sal,
nvl(e.sal - lag(e.sal) over(partition by e.deptno order by e.sal), 0) diff_lag_sal
from scott.emp e; 

lag(列名,n,m):  当前记录前面第n行记录的<列名>的值，没有则默认值为m；如果不带参数n,m，则查找当前记录前面第一行的记录<列名>的值，没有则默认值为null。

  select e.ename,
e.job,
e.sal,
e.deptno,
first_value(e.sal) over(partition by e.deptno) first_sal,
last_value(e.sal) over(partition by e.deptno) last_sal,
sum(e.sal) over(partition by e.deptno) sum_sal,
avg(e.sal) over(partition by e.deptno) avg_sal,
count(e.sal) over(partition by e.deptno) count_num,
row_number() over(partition by e.deptno order by e.sal) row_num
from scott.emp e;

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。