[LeetCode] Employees Earning More Than Their Managers 員工掙得比經理多


 

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

+----+-------+--------+-----------+
| Id | Name  | Salary | ManagerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
+----+-------+--------+-----------+

Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.

+----------+
| Employee |
+----------+
| Joe      |
+----------+

 

這道題給我們了一個Employee表,里面有員工的薪水信息和其經理的信息,經理也屬於員工,其經理Id為空,讓我們找出薪水比其經理高的員工,那么就是一個很簡單的比較問題了,我們可以生成兩個實例對象進行內交通過ManagerId和Id,然后限制條件是一個Salary大於另一個即可:

 

解法一:

SELECT e1.Name FROM Employee e1
JOIN Employee e2 ON e1.ManagerId = e2.Id
WHERE e1.Salary > e2.Salary;

 

我們也可以不用Join,直接把條件都寫到where里也行:

 

解法二:

SELECT e1.Name FROM Employee e1, Employee e2
WHERE e1.ManagerId = e2.Id AND e1.Salary > e2.Salary;

 

參考資料:

https://leetcode.com/discuss/88189/two-straightforward-way-using-where-and-join

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM