leetcode刷題筆記一百八十四題 && 一百八十五題
leetcode刷題筆記一百八十四題 && 一百八十五題
源地址:
184問題描述:
Employee 表包含所有員工資訊,每個員工有其對應的 Id, salary 和 department Id。
+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Jim | 90000 | 1 |
| 3 | Henry | 80000 | 2 |
| 4 | Sam | 60000 | 2 |
| 5 | Max | 90000 | 1 |
+----+-------+--------+--------------+
Department 表包含公司所有部門的資訊。+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
編寫一個 SQL 查詢,找出每個部門工資最高的員工。對於上述表,您的 SQL 查詢應返回以下行(行的順序無關緊要)。+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Jim | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
解釋:Max 和 Jim 在 IT 部門的工資都是最高的,Henry 在銷售部的工資最高。
# Write your MySQL query statement below SELECT B.name AS 'Department', A.name AS 'Employee', Salary FROM Employee AS A JOIN Department B ON A.DepartmentId = B.Id WHERE (A.DepartmentId , A.Salary) IN ( SELECT DepartmentId, MAX(Salary) FROM Employee GROUP BY DepartmentId );
185問題描述:
SQL架構
Employee
表包含所有員工資訊,每個員工有其對應的工號Id
,姓名Name
,工資Salary
和部門編號DepartmentId
。+----+-------+--------+--------------+ | Id | Name | Salary | DepartmentId | +----+-------+--------+--------------+ | 1 | Joe | 85000 | 1 | | 2 | Henry | 80000 | 2 | | 3 | Sam | 60000 | 2 | | 4 | Max | 90000 | 1 | | 5 | Janet | 69000 | 1 | | 6 | Randy | 85000 | 1 | | 7 | Will | 70000 | 1 | +----+-------+--------+--------------+
Department
表包含公司所有部門的資訊。+----+----------+ | Id | Name | +----+----------+ | 1 | IT | | 2 | Sales | +----+----------+
編寫一個 SQL 查詢,找出每個部門獲得前三高工資的所有員工。例如,根據上述給定的表,查詢結果應返回:
+------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Max | 90000 | | IT | Randy | 85000 | | IT | Joe | 85000 | | IT | Will | 70000 | | Sales | Henry | 80000 | | Sales | Sam | 60000 | +------------+----------+--------+
解釋:
IT 部門中,Max 獲得了最高的工資,Randy 和 Joe 都拿到了第二高的工資,Will 的工資排第三。銷售部門(Sales)只有兩名員工,Henry 的工資最高,Sam 的工資排第二。
# Write your MySQL query statement below
SELECT B.Name AS Department, A.Name AS Employee,A.Salary FROM
(SELECT dense_rank() OVER(PARTITION BY DepartmentId ORDER BY Salary DESC) AS RANKId, Name, Salary, DepartmentId FROM Employee) AS A JOIN Department AS B
ON A.DepartmentId = B.Id WHERE A.RANKId <= 3;