LeetCode之部门工资前三高的员工

有表
department
在这里插入图片描述
Employee
在这里插入图片描述
编写一个 SQL 查询,找出每个部门工资前三高的员工。例如,根据上述给定的表格,查询结果应返回:

±-----------±---------±-------+
| Department | Employee | Salary |
±-----------±---------±-------+
| IT | Max | 90000 |
| IT | Randy | 85000 |
| IT | Joe | 70000 |
| Sales | Henry | 80000 |
| Sales | Sam | 60000 |
±-----------±---------±-------+

我的答案:
select
d.Name as Department,
e.Name as Employee,
e.Salary as Salary
from
Employee e inner join Department d
on e.departmentId=d.id
where
(
select count(distinct e2.salary)
from employee as e2
where e.departmentId=e2.departmentId
and
e.salary<=e2.salary
) <=3
order by e.departmentId,e.salary desc

涉及到的知识点:
(1)inner join通过on 条件联系两个表,如果遇到不符合条件的on则不符合条件的那一行将不会被显示(这是和left join的区别)
(2)order by 多个字段时,会从前往后依次根据需要排序的字段进行排序。
例如 order by e.departmentId,e.salary desc
含义是先根据departmentId排序,然后在departmentId排序后的每个小分组中对salary进行子排序

语句逻辑:
(1)根据部门id内联 Employee 和 Department :
Employee e inner join Department d
on e.departmentId=d.id
(2)针对每一条内联后的数据,我们对其进行子查询判断是否在其部门工资排名前三:
(
select count(distinct e2.salary)
from employee as e2
where e.departmentId=e2.departmentId
and
e.salary<=e2.salary #子查询条件
) <=3 #某条记录在子查询中工资数大于自己的数量不超过三个就是排名前三
(3)给部门分组,并对每个小组进行排序
order by e.departmentId,e.salary desc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值