Leetcode刷SQL 2 部門工資最高的員工

2022-03-03 09:29:27 字數 1587 閱讀 6529

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 |

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

本題存在以下幾個麻煩點:

1、按照部門分類查詢工資最高的

2、可能存在多個人會有相同的最高工資

3、部門和員工不對應(這點值得吐槽)

select

d.name as department,

e2.name as employee,

e2.salary as salary

from

department d

left join employee e2

on e2.departmentid = d.id

right join

(select

e.departmentid,

max(e.`salary`) as salary

from

employee e

group by e.`departmentid`) e1 //查詢最高薪水

on e1.salary = e2.`salary`

and e1.departmentid = e2.`departmentid`

where e2.id is not null

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

184 部門工資最高的員工

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

184 部門工資最高的員工

原始資料 嘗試找出最大值,但是出現了一些問題,名字和salary對應不上。明明是jim的工資9000,但是這裡輸出的是joe,why?看了下面這個帖子 自己寫的正確答案思路 先找出最大工資記錄,然後匹配回原表,這樣就不會出錯了 接下來與第二張表進行連線,把部門名稱得到 下面貼出官方解法,思路基本一樣...