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