我需要使用相关子查询和 oracle sql 获取每个部门第二高的薪水

I need to fetch the second highest salary per department using correlated subquery and oracle sql

如果我运行这样的代码我得到了我需要的结果,但我还需要添加名称列,一旦我添加它,结果就会改变

select  department_id, max(salary)
from employees e1
where salary < 
(select max(salary) 
from employees e2
where e2.department_id=e1.department_id)
group by department_id
order by department_id;

您可以将 row_number() window 函数与普通 table 表达式一起使用,而不是使用子查询:

with cte as
(
  select  department_id, row_number()over(partition by department_id order by salary 
  desc) rn, name 
  from employees e1
)
select  department_id, salary, name 
from cte where rn=2

只需在 select 列表中添加名称列即可解决问题

select  department_id, max(salary),name
from employees e1
where salary < 
(select max(salary) 
from employees e2
where e2.department_id=e1.department_id)
group by department_id
order by department_id;

我没有你的桌子,所以我会用 Scott 的 EMP。这是它的内容:

SQL> select deptno, ename, sal from emp order by deptno, sal desc;

    DEPTNO ENAME             SAL
---------- ---------- ----------
        10 KING             5000
        10 CLARK            2450   --> 2nd highest in deptno 10
        10 MILLER           1300
        20 SCOTT            3000
        20 FORD             3000
        20 JONES            2975   --> 2nd highest in deptno 20
        20 ADAMS            1100
        20 SMITH             800
        30 BLAKE            2850
        30 ALLEN            1600   --> 2nd highest in deptno 30
        30 TURNER           1500
        30 MARTIN           1250
        30 WARD             1250
        30 JAMES             950

14 rows selected.

这是你不想要的:

SQL> with temp as
  2    (select deptno, ename, sal,
  3       dense_rank() over (partition by deptno order by sal desc) rnk
  4     from emp
  5    )
  6  select *
  7  from temp
  8  where rnk = 2
  9  order by deptno, sal desc;

    DEPTNO ENAME             SAL        RNK
---------- ---------- ---------- ----------
        10 CLARK            2450          2
        20 JONES            2975          2
        30 ALLEN            1600          2

SQL>

好的,让我们关联一些子查询,然后。 Return 名员工的薪水为

  • 低于他们部门的最高水平(第 6 行)(它将排名第一)
  • 他们部门其他人的最高工资(第 3 行)

所以:

SQL> select e.deptno, e.ename, e.sal
  2  from emp e
  3  where e.sal = (select max(b.sal)
  4                 from emp b
  5                 where b.deptno = e.deptno
  6                   and b.sal < (select max(a.sal)
  7                                from emp a
  8                                where a.deptno = b.deptno
  9                                group by a.deptno
 10                               )
 11                 )
 12  order by e.deptno;

    DEPTNO ENAME             SAL
---------- ---------- ----------
        10 CLARK            2450
        20 JONES            2975
        30 ALLEN            1600

SQL>