原題:https://leetcode-cn.com/problems/department-highest-salary/
我自己做leetcode的數據庫題目的解題記錄:
解題目錄 https://blog.csdn.net/weixin_42845682/article/details/105196004
題目描述:
Employee 表包含所有員工信息,每個員工有其對應的 Id, salary 和 department Id。
+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
+----+-------+--------+--------------+
Department 表包含公司所有部門的信息。
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
編寫一個 SQL 查詢,找出每個部門工資最高的員工。例如,根據上述給定的表格,Max 在 IT 部門有最高工資,Henry 在 Sales 部門有最高工資。
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
答案:
第一種答案
一開始感覺這道題很簡單,後來發現有點難。如果讓我來設計表結構,我肯定要把薪酬表和員工個人信息表分開。
select
department Department,
e1.name Employee,
tmp.salary Salary
from employee e1
join (
select
d.name department,
d.id id,
max(salary) salary
from employee e
join department d on e.departmentId = d.id
group by d.name,d.id
) tmp on e1.salary = tmp.salary and e1.departmentId = tmp.id
group by tmp.department, e1.name
雖然寫出來了,也通過測試了,但是看着總覺得哪裏怪怪的。
思路是:先找出部門最高的工資,然後用部門和工資去join,employee表(因爲有可能出現幾個部門最高工資是一樣的,所以用部門加工資)。
但是怎麼說呢,總感覺顯示員工名字怪怪的,不考慮重名嗎?而且題目也沒說,如果一個部門有兩個人並列工資最高應該怎麼顯示,煩。
第二種答案
其實這種分段排序,用row_number()也能做。
select
dname department,
ename employee,
salary
from(
select
d.name dname,
e.name ename,
e.salary,
row_number() over(partition by d.name order by salary desc) row_num
from employee e
join department d on e.departmentId=d.id
) tmp
where row_num = 1
提交的時候,出錯了。看了一下,預期輸出結果:如果部門有兩個工資一樣高的,那麼要把兩個人都輸出。那row_number()肯定是不行了。。。
不過也好改,改成dense_rank()或者rank()都行。
select
dname department,
ename employee,
salary
from(
select
d.name dname,
e.name ename,
e.salary,
dense_rank() over(partition by d.name order by salary desc) row_num
from employee e
join department d on e.departmentId=d.id
) tmp
where row_num = 1
吐槽一下:這些重合的數據怎麼處理沒有具體的說明;oracle提交也是真的麻煩…一直超時
得瑟一下:
看來我寫的這個,效率還蠻高的。