**部门工资前三的员工

1

2

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

思路

①通过表1的departmentId和表2的Id相连
②用group by对部门进行分组
③通过表1与表1之间的比较得到部门工资前3的员工
前3高意味着不超过3个人的工资比这些值大

SELECT Department.Name AS Department, e1.Name AS Employee, e1.Salary AS Salary
FROM Employee e1
JOIN Department
ON e1.DepartmentId = Department.Id
WHERE 3 > (
SELECT COUNT(DISTINCT e2.Salary) 
FROM Employee e2
WHERE e2.Salary > e1.Salary AND e1.DepartmentId = e2.DepartmentId
)
ORDER BY Department.Name, e1.Salary DESC

假设e1=e2=[6,5,4,3],则子查询的过程如下:
1、e1.Salary=3;则e2.Salary可以取4、5、6;COUNT(DISTINCT e2.Salary)=3
2、e1.Salary=4;则e2.Salary可以取5、6;COUNT(DISTINCT e2.Salary)=2
3、e1.Salary=5;则e2.Salary可以取6;COUNT(DISTINCT e2.Salary)=1
4、e1.Salary=6;则e2.Salary无法取值;COUNT(DISTINCT e2.Salary)=0
则要令COUNT(DISTINCT e2.Salary) < 3 的情况有上述的4、3、2.
也即是说,这等价于取e1.Salary最大的三个值。

你可能感兴趣的:(**部门工资前三的员工)