[LeetCode] Department Highest & Top 3 Salary - SQL

The Employee table holds all employees. Every employee has an Id, a salary, 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            |
+----+-------+--------+--------------+

The Department table holds all departments of the company.

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

1. Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department.

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| Sales      | Henry    | 80000  |
+------------+----------+--------+

解題思路:

首先查詢出每一個部門的最高薪水,然後使用薪水值和部門Id與僱員表Employee做內連接,再通過部門Id與部門表Department做內連接。

# Write your MySQL query statement below
SELECT d.Name AS Department, e.Name AS Employee, t.Salary 
FROM   Employee e 
INNER JOIN 
(SELECT DepartmentId, MAX(Salary) AS Salary FROM Employee GROUP BY DepartmentId) t
USING(DepartmentId, Salary)
INNER JOIN 
Department d
ON d.id = t.DepartmentId

2. 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  |

+------------+----------+--------+

解題思路:

首先使用Salary和DepartmentId將Employee e1和Employee e2(過濾掉每組內重複的Salary)作內聯接(e2.Salary >= e1.Salary);

然後再與Department作內聯接獲得DepartmentName

最後根據返回結果中的e1.Id分組,過濾出Id出現次數小於4的即是結果。

select d.Name as Department, e1.Name as Employee, e1.Salary 
from Employee e1 
join 
(select Salary, DepartmentId from Employee group by DepartmentId, Salary) e2
on e1.Salary <= e2.Salary and e1.DepartmentId = e2.DepartmentId
join 
Department d 
on e1.DepartmentId = d.Id 
group by e1.Id 
having count(e1.Id) < 4 
order by d.Id, Salary DESC;



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章