Employee
表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id 。
Department
表包含公司所有部门的信息。
编写一个 SQL 查询,找出每个部门工资前三高的员工。例如,根据上述给定的表格,查询结果应返回:
解答:
SELECT
Department,
Employee,
Salary
FROM
(
SELECT Department,Employee,Salary,
@rowNum :=IF(@LastD = t.Department,@rowNum + ( @lastS <> t.Salary ),1 ) AS seq,
@lastD := t.Department,
@lastS := t.Salary
FROM
(SELECT d.NAME Department,e.NAME Employee,Salary
FROM Employee e,Department d
WHERE e.DepartmentId = d.Id
ORDER BY d.NAME,Salary DESC ) t,
(SELECT @lastD:= -1,@lastS:= -1,@rowNum:= 0 ) AS init
) AS t2
WHERE t2.seq <= 3;