部门工资前三高的员工

Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 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            |
+----+-------+--------+--------------+
Department 表包含公司所有部门的信息。
+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

编写一个 SQL 查询,找出每个部门工资前三高的员工

Code

  1. (select count(distinct(salary)) from employee
    where departmentid = e.departmentid and salary>e.salary)< 3
    1. 嵌套员工表作为过滤表
    2. e表的工资限制 = 与过滤表的比较 + 过滤表工资数目的限制
select d.name department, e.name employee, e.salary 
from employee e inner join department d on e.departmentid = d.id 
where 
(select count(distinct(salary)) from employee 
	where departmentid = e.departmentid and salary>e.salary)< 3
order by e.departmentid, e.salary desc

猜你喜欢

转载自blog.csdn.net/sgs595595/article/details/89074876