SQL-显示每个部门的第二高薪水,如果员工的薪水相同,则显示最低empno薪水

时间:2019-04-20 17:36:37

标签: sql greatest-n-per-group

我需要为每个部门显示第二高的薪水,如果员工的薪水相同,则显示最低empno的薪水。

我有一个emp下表,其中deptno 20的两个empno 7788和7902拥有第二高的工资。

EMPNO   ENAME   JOB  SAL    DEPTNO
7698    BLAKE   MANAGER  2850   30
7844    TURNER  SALESMAN 1500   30
7499    ALLEN   SALESMAN 1600   30
7654    MARTIN  SALESMAN 1250   30
7521    WARD    SALESMAN 1250   30
7900    JAMES   CLERK    950    30
7788    SCOTT   ANALYST  3000   20
7566    JONES   MANAGER  2975   20
7369    SMITH   CLERK    25000  20
7876    ADAMS   CLERK    1100   20
7902    FORD    ANALYST  3000   20
7839    KING    PRESIDENT 5000  10
7934    MILLER  CLERK    1300   10
7782    CLARK   MANAGER  2450   10

我写了下面的代码:

select * from (
  select e.*, row_number() over (partition by deptno order by sal desc ) rn 
  from emp e  
)where rn = 2;

我的成绩不及格。但是根据我的要求,如果该部门的任何员工的薪水相同,则应显示员工编号最少的薪水,但在我的情况下,将显示empno 7902。但是我需要使用empno 7788显示薪水:

EMPNO   ENAME   JOB       SAL   DEPTNO
7782    CLARK   MANAGER   2450  10
7902    FORD    ANALYST   3000  20
7499    ALLEN   SALESMAN  1600  30

如何实现?

3 个答案:

答案 0 :(得分:1)

尝试一下。

您必须使用asc的子句添加empno

    select * from ( select e.*, row_number() over (partition by deptno order by 
    sal desc,empno asc ) rn 
    from emp e) where rn = 2;

答案 1 :(得分:1)

此查询在MySql上给出正确的结果

select * from (
    select e.*, row_number() over (partition by deptno order by sal desc, empno asc ) rn 
    from emp e  
) s where rn = 2;

结果

EMPNO   ENAME   JOB         SAL     DEPTNO  rn  
7782    CLARK   MANAGER     2450    10      2  
7788    SCOTT   ANALYST     3000    20      2   
7499    ALLEN   SALESMAN    1600    30      2

dbfiddle using Oracle

答案 2 :(得分:0)

您可以使用RANK()RANK()ROW_NUMBER()之间的区别在于RANK()将为相同的数字赋予相同的排名,因此您将看到部门20的两个2。然后将其与另一个部门合并ROW_NUMBER()获得最少的EMPNO:

SELECT * FROM (
SELECT
  subq.EMPNO,
  subq.DEPTNO,
  ROW_NUMBER() OVER(PARTITION BY subq.DEPTNO ORDER BY EMPNO ASC) AS empno_rownum
FROM (  
  SELECT 
    salary.EMPNO,
    salary.DEPTNO,
    RANK() OVER(PARTITION BY salary.DEPTNO ORDER BY salary.SAL DESC) AS salary_rank
  FROM salary
) AS subq
WHERE subq.salary_rank = 2
) AS subq2
WHERE subq2.empno_rownum = 1

结果如下:

EMPNO   DEPTNO  salary_rank
7782    10  2
7788    20  2
7499    30  2