题解 | #获取当前薪水第二多的员工的emp_no以及其对应的薪水salary#
获取当前薪水第二多的员工的emp_no以及其对应的薪水salary
https://www.nowcoder.com/practice/c1472daba75d4635b7f8540b837cc719
获取当前薪水第二多的员工的emp_no以及其对应的薪水salary🈲order by
思路:先取一次工资最大值,去掉,然后再取剩余最大值
易错点:
- 不能在where里面写聚合函数,必须用子查询,否则聚合函数还没出来不能用where筛选;
- 不能连写两个with,多个CTE子查询必须写在一个CTE下面
WITH
M AS (
SELECT MAX(salary) AS max_sal
FROM salaries
),
second_top AS (
...
)
SELECT ...
- CTE 中不能直接引用另一个 CTE 的列。如以下是错误的:
with M as (
select max(salaries.salary) as max_sal
from salaries ),
second_top as (
select max(s.salary)
from salary s where s.salary < M.max_sal )
// wrong! 这里 M.max_sal 没有出现在 FROM 里,所以找不到。
完整正确写法:
with no_top as (
select s.salary from salaries s
where s.salary < (select max(s.salary) from salaries s)
)
select e.emp_no, s.salary, e.last_name, e.first_name from employees e inner join salaries s on e.emp_no = s.emp_no
where s.salary = (select max(no_top.salary) from no_top)

