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



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