sql查询找到公司前5名收入者(oracle db)

时间:2017-11-09 07:42:46

标签: sql oracle oracle10g greatest-n-per-group

我的emp表:

ENAME             SAL
---------- ----------
KING             5000
SCOTT            3000
FORD             3000
JONES            2975
BLAKE            2850
CLARK            2450

获得前5名收入者。我使用了以下查询。

SELECT  * 
FROM (SELECT ename, sal 
     from emp 
     ORDER BY sal desc)
WHERE rownum <= 5  
order by sal desc;

但是我得到这样的输出:

ENAME             SAL
---------- ----------
KING             5000
SCOTT            3000
FORD             3000
JONES            2975
BLAKE            2850

在此列表中,&#39; CLARK&#39;不见了。

员工&#39; CLARK&#39;也列在前5名收入者列表中。如果列表中有相同的工资,我会得到。 如果我使用dense_rank,&#39; CLARK&#39;将列入名单。

 SELECT  *  from 
(SELECT ename,SAL,DENSE_RANK() OVER(ORDER BY SAL DESC) AS RK FROM EMP)
WHERE RK <= 5
ORDER BY SAL DESC;



ENAME             SAL         RK
---------- ---------- ----------
KING             5000          1
SCOTT            3000          2
FORD             3000          2
JONES            2975          3
BLAKE            2850          4
CLARK            2450          5

3 个答案:

答案 0 :(得分:0)

这是一个SQL SERVER查询。希望它对你有帮助,

    SELECT Ename, Sal
    FROM     
        (
        SELECT ename, sal,DENSE_RANK() OVER(ORDER BY Sal DESC)RN from emp ORDER BY sal desc
        )D
    WHERE RN <= 5  
    ORDER BY sal desc;

如果没有DENSE_RANK,请尝试以下答案:

    SELECT Ename, Sal
    FROM emp
    WHERE sal IN(
        SELECT TOP 5 sal
        FROM @emp GROUP BY sal
        ORDER by sal DESC)

答案 1 :(得分:0)

包括关系:

SELECT ename, sal 
from emp 
ORDER BY sal desc
fetch first 5 rows with ties

排除关系:

... fetch first 5 rows only

ANSI SQL,由较新的Oracle版本支持。 (我不知道它是否在10克。)

答案 2 :(得分:0)

确定内部选择中的前五名工资:

select e.ename, e.sal
  from emp e
 where e.sal in
       (select ee.sal
          from emp ee
         group by ee.sal
         order by ee.sal desc fetch first 5 rows only) -- top 5 salaries
 order by e.sal desc, e.ename asc;