Oracle keep详解
原题目
select * from dept where deptno=(select max(deptno) keep(dense_rank last order by count(1))
from emp group by deptno);
解析:
select max(deptno) keep(dense_rank last order by count(1) 拆分成select deptno,max(deptno) keep(dense_rank last order by count(1)
这里的order by count(1) 可以看成select deptno,count(1) group by dept no,也就是说 order by count(1)是按deptno的count的值进行排序的,排序后看KEEP LAST 还是FIRST,如果是last则看后面的,比如说select deptno,max(deptno) keep(dense_rank last order by count(1)查询出来是下面的
deptno count(1)
2 1
5 1
3 2
1 3
4 3
则这里是last,则看最后,则他要最大值,而这里有两个最大值3,则取出来是select max(deptno) keep(dense_rank last order by count(1)取出来是
deptno
1
4
(如果是first
deptno
2
5
)
而取出来的值在按deptno 升序排序且是max结果是
deptno
4
然后在与dept表 结合的。
在这里感谢群友kaka详细的解释