以Oracle hr模式的employees表为例。
查询每个部门收入最多的前三个人。
实验数据初始化:
-
create table test as select * from hr.employees;
方法一:
-
select department_id,last_name,salary
-
from test t1
-
where
-
(
-
select count(*) from test t2
-
where t2.department_id=t1.department_id and t1.salary<t2.salary
-
) < 3 order by department_id,salary desc;
增加索引
方法二:(Oracle分析函数)
-
select department_id,last_name,salary from
-
(
-
select department_id,last_name,salary,
-
row_number() over(partition by department_id order by salary desc) r
-
from test
-
) where r<=3;
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1142071/
,如需转载,请注明出处,否则将追究法律责任。