Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id 。

    image.png

    Department 表包含公司所有部门的信息。

    image.png

    编写一个 SQL 查询,找出每个部门工资前三高的员工。例如,根据上述给定的表格,查询结果应返回:

    image.png

    解答:

    1. SELECT
    2. Department,
    3. Employee,
    4. Salary
    5. FROM
    6. (
    7. SELECT Department,Employee,Salary,
    8. @rowNum :=IF(@LastD = t.Department,@rowNum + ( @lastS <> t.Salary ),1 ) AS seq,
    9. @lastD := t.Department,
    10. @lastS := t.Salary
    11. FROM
    12. (SELECT d.NAME Department,e.NAME Employee,Salary
    13. FROM Employee e,Department d
    14. WHERE e.DepartmentId = d.Id
    15. ORDER BY d.NAME,Salary DESC ) t,
    16. (SELECT @lastD:= -1,@lastS:= -1,@rowNum:= 0 ) AS init
    17. ) AS t2
    18. WHERE t2.seq <= 3;