Oracle查询以获取每个部门的前3名工资

时间:2016-04-29 08:19:03

标签: oracle subquery

我想要一个SQL查询来获取每个部门的前三名工资

Table :- sample

Name   Salary   Dept
AA      1000    Hr
BB      7520    Store
CC     12500    Hr
DD      9850    Store
EE     10250    Finance
FF     12560    Hr
GG     13500    Store
HH     15680    Store
KK     12853    Hr
MM     17582    Finance
NN     16852    Finance 

我使用了以下查询,但没有获取正确的结果

SELECT dept, fname,lname,sal from sample where rownum<4 group by(fname,lname,sal,desg) order by sal desc

4 个答案:

答案 0 :(得分:2)

您需要的是分析函数row_number

select * 
from (select a.*, row_number() over (PARTITION by dept order by salary desc) as num 
        from sample a
)
where num < 4;

答案 1 :(得分:0)

尝试group by,然后where rownum < 4

SELECT dept,fname,lname,sal 
FROM sample 
GROUP BY(fname,lname,sal,desg)
WHERE ROWNUM < 4
ORDER BY sal DESC
; 

同时选中SELECTGROUP BY列作为仅显示NAME的表格,而不是fnamelname

答案 2 :(得分:0)

SELECT * 
FROM(SELECT Name  ,Dept ,Salary  , 
DENSE_RANK() OVER (PARTITION BY Dept ORDER BY Salary  DESC)AS D_RANK 
FROM sample ) 
WHERE D_RANK <=3;

答案 3 :(得分:0)

SELECT *
FROM sample a
WHERE
   3 >= ( SELECT COUNT(DISTINCT salary)
          FROM sample b
          WHERE a.salary <= b.salary
            AND a.dept = b.dept
        )