您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關SQL中怎么利用LeetCode求前三高薪水,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
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 |
+------------+----------+--------+
這道題是之前那道Department Highest Salary的拓展,難度標記為Hard,還是蠻有難度的一道題,綜合了前面很多題的知識點,首先看使用Select Count(Distinct)的方法,我們內交Employee和Department兩張表,然后我們找出比當前薪水高的最多只能有兩個,那么前三高的都能被取出來了,參見代碼如下:
解法一:
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;
下面這種方法將上面方法中的<3換成了IN (0, 1, 2),是一樣的效果:
解法二:
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;
或者我們也可以使用Group by Having Count(Distinct ..) 關鍵字來做:
解法三:
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;
下面這種方法略微復雜一些,用到了變量,跟Consecutive Numbers中的解法三使用的方法一樣,目的是為了給每個人都按照薪水的高低增加一個rank,最后返回rank值小于等于3的項即可,參見代碼如下:
解法四:
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;
看完上述內容,你們對SQL中怎么利用LeetCode求前三高薪水有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。