sql查询每个部门前三高工资的员工

Employee 表包含所有员工信息,每个员工有其对应的工号 Id,姓名 Name,工资 Salary 和部门编号 DepartmentId。

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 85000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
| 7  | Will  | 70000  | 1            |
+----+-------+--------+--------------+

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

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+
编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Randy    | 85000  |
| IT         | Joe      | 85000  |
| IT         | Will     | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
+------------+----------+--------+

sql:

第一种实现:

SELECT
    d.NAME AS Department,
    e.NAME AS Employee,
    e.Salary AS Salary 
FROM
    Employee AS e
    LEFT JOIN Department AS d ON e.DepartmentId = d.Id 
WHERE
    e.Id IN (
    SELECT
        e1.Id 
    FROM
        Employee AS e1
        LEFT JOIN Employee AS e2 ON e1.DepartmentId = e2.DepartmentId 
        AND e1.Salary < e2.Salary 
    GROUP BY
        e1.Id 
    HAVING
        count( DISTINCT e2.Salary ) <= 2 
    ) 
ORDER BY
    d.Id ASC,
    e.Salary DESC;

第二种实现:

SELECT

    d.Name AS 'Department', e1.Name AS 'Employee', e1.Salary

FROM

    Employee e1

        JOIN

    Department d ON e1.DepartmentId = d.Id

WHERE

    3 > (SELECT

            COUNT(DISTINCT e2.Salary)

        FROM

            Employee e2

        WHERE

            e2.Salary > e1.Salary

                AND e1.DepartmentId = e2.DepartmentId

        )

具体的实现思路就是按着本部门薪资降序排序,去重后取前三名,

第一种实现思路为GROUP BY having  count()原理 

第二种实现思路为 DISTINCT 去重取前三 原理

你可能感兴趣的:(mysql)