码疯窝

LeetCode 每日一题 — Department Top Three Salaries

2015/01/26 10:06:28    分类: 日志连载    1人评论 次浏览

The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.

+----+-------+--------+--------------+
| 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            |
+----+-------+--------+--------------+

The Department table holds all departments of the company.

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows.

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

分析: 总算出现了一道难度系数为Hard的SQL题目, 可以一看题目却是不尽人意. 思路很简单, 因为之前做过求 Nth Highest Salary, 所以我们只需要求出rank <= 3的即是结果. rank 怎么求的? 对Employee表 Order by DepartmentId, Salary Desc 后, 得到顺序表, 然后判断

if (DepartmentId = prevousDepartmentId)
    rank = (Salary != prevousSalary) ? rank + 1 : rank;
else 
    rank = 1;

原理如此, 换成程序语言就是这么理解.

SELECT d.Name AS Department, cte.Name AS Employee, cte.Salary
FROM (
	SELECT t.*, if(t.DepartmentId = @pred, if (t.Salary = @pres, @rank, @rank := @rank + 1), @rank := 1) AS rank, @pred := t.DepartmentId, @pres := t.Salary
	FROM Employee t, (SELECT @rank := 0, @pred := 0, @pres := 0) r
	ORDER BY DepartmentId, Salary DESC
) cte
INNER JOIN Department d
ON d.Id = cte.DepartmentId
WHERE cte.rank <= 3
ORDER BY d.Id, cte.Salary DESC
继续查看有关 日志连载的文章

1个访客评论

  1. 风流鬼

    仔细拜读,表示支持!

    甲午年(马)腊月初九 2015-1-28

    qweqwe Reply