Department Top Three Salaries

原题: https://leetcode.com/problems/department-top-three-salaries/description/

题意: 雇员表Employee保存了雇员的Id,姓名,薪水,以及部门Id。部门表Department保存了部门的Id和名称。编写一个SQL查询找出每一个部门薪水排名前3位的雇员信息(排名可以并列)。

例子: 

雇员表:
+----+-------+--------+--------------+
| 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            |
+----+-------+--------+--------------+

部门表:
+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

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

标签: department、雇员、sales、salaries、randy、面试
猜你感兴趣的圈子:
LeetCode交流圈
  • Bingo
    2017-08-17 17:21:20 1楼#1层
    解法一:
    SELECT d.Name AS Department, e.Name AS Employee, e.Salary FROM Employee e
    JOIN Department d on e.DepartmentId = d.Id
    WHERE (SELECT COUNT(DISTINCT Salary) FROM Employee WHERE Salary > e.Salary
    AND DepartmentId = d.Id) < 3 ORDER BY d.Name, e.Salary DESC;
  • Bingo
    2017-08-17 17:21:38 2楼#1层
    解法二:
    SELECT d.Name AS Department, e.Name AS Employee, e.Salary FROM Employee e, Department d
    WHERE (SELECT COUNT(DISTINCT Salary) FROM Employee WHERE Salary > e.Salary
    AND DepartmentId = d.Id) IN (0, 1, 2) AND e.DepartmentId = d.Id ORDER BY d.Name, e.Salary DESC;
  • Bingo
    2017-08-17 17:21:52 3楼#1层
    解法三:
    SELECT d.Name AS Department, e.Name AS Employee, e.Salary FROM 
    (SELECT e1.Name, e1.Salary, e1.DepartmentId FROM Employee e1 JOIN Employee e2 
    ON e1.DepartmentId = e2.DepartmentId AND e1.Salary <= e2.Salary GROUP BY e1.Id 
    HAVING COUNT(DISTINCT e2.Salary) <= 3) e JOIN Department d ON e.DepartmentId = d.Id 
    ORDER BY d.Name, e.Salary DESC;
  • Bingo
    2017-08-17 17:22:05 4楼#1层
    解法四:
    SELECT d.Name AS Department, e.Name AS Employee, e.Salary FROM 
    (SELECT Name, Salary, DepartmentId,
    @rank := IF(@pre_d = DepartmentId, @rank + (@pre_s <> Salary), 1) AS rank,
    @pre_d := DepartmentId, @pre_s := Salary 
    FROM Employee, (SELECT @pre_d := -1, @pre_s := -1, @rank := 1) AS init
    ORDER BY DepartmentId, Salary DESC) e JOIN Department d ON e.DepartmentId = d.Id
    WHERE e.rank <= 3 ORDER BY d.Name, e.Salary DESC;
  • 回复
隐藏