1. 程式人生 > >[LeetCode] Employees Earning More Than Their Managers 員工掙得比經理多

[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;

參考資料: