题解 | #获取当前薪水第二多的员工的emp_no以及其对应的薪水salary#

获取当前薪水第二多的员工的emp_no以及其对应的薪水salary

https://www.nowcoder.com/practice/c1472daba75d4635b7f8540b837cc719

获取当前薪水第二多的员工的emp_no以及其对应的薪水salary🈲order by

思路:先取一次工资最大值,去掉,然后再取剩余最大值
易错点:

  1. 不能在where里面写聚合函数,必须用子查询,否则聚合函数还没出来不能用where筛选;
  2. 不能连写两个with,多个CTE子查询必须写在一个CTE下面
WITH
M AS (
    SELECT MAX(salary) AS max_sal
    FROM salaries
),
second_top AS (
    ...
)
SELECT ...
  1. 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)
全部评论

相关推荐

牛客52811839...:有的hr就是这样啊,很正常。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务