Department Top Three Salaries


The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.
+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
+----+-------+--------+--------------+

The Department table holds all departments of the company.

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows.

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Randy    | 85000  |
| IT         | Joe      | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
+------------+----------+--------+
题意:有两张表,一个是员工表,一个部门表,求各个部分的工资前3名的
思路:先创建一个临时表其中包含部门排名,再与员工表连接得到包含部门排名的表,最后与部门表连接得到结果
select d.Name,e3.Name,e3.Salary from ( select distinct e1.Name,e1.DepartmentId,e1.Salary,e2.Rank from Employee e1, ( select e1.Salary ,e1.DEPARTMENTID,COUNT(*) as Rank from (select distinct Salary,DepartmentId from Employee) e1,(select distinct Salary,DepartmentId from Employee) e2
 where e1.Salary <= e2.Salary and e1.DEPARTMENTID=e2.DEPARTMENTID Group by e1.Salary ,e1.DEPARTMENTID

) e2 where e1.Salary=e2.Salary and e1.DepartmentId=e2.DepartmentId ) e3,Department d where e3.rank<=3 and d.Id=e3.DepartmentId order by DepartmentId,Salary desc

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值