日誌2023-09-07 19:12
【Leetcode】184. Department Highest Salary作者:Chris
Employee表格屬性 | |
Column Name | Type |
id | int |
name | varchar |
salary | int |
departmentId | int |
Department表格屬性 | |
Column Name | Type |
id | name |
name | varchar |
id | name | salary | departmentId |
1 | Joe | 70000 | 1 |
2 | Jim | 90000 | 1 |
3 | Henry | 80000 | 2 |
4 | Sam | 60000 | 2 |
5 | Max | 90000 | 1 |
id | name |
1 | IT |
2 | Sales |
Department | Employee | Salary |
IT | Jim | 90000 |
Sales | Henry | 80000 |
IT | Max | 90000 |
個人理解 |
這邊使用Left Join語法將兩個資料表組合在一起,再使用Max語法找出最大數值,再使用Where把最大數值挑出來,就會剩下第二高的數值。 這裡著重於使用Where(columns name)In(要選擇的值)、Max函數,以及雙層Select,這裡個人理解成類似巢狀迴圈的模式。 |
程式碼 |
select Department.name as Department, Employee.name as Employee, Employee.Salary as Salary from Employee left join Department #inner join也可 on Employee.departmentId = Department.id where (Department.id, Employee.Salary) in ( select departmentId, max(Salary) from Employee group by departmentId ) #where (COLUMNS) in (需要放的值)0 |