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 |
【Life】 (0)
└Composition (4)
└Technology (10)
└Picture (5)
└Diary (14)
└Game (0)
【RPG_Guild】 (1)
└Character (4)
└Setting (6)
└Story (0)
【箱庭_Guild】 (0)
└Character (5)
└Setting (9)
└Story (2)
└Item (4)
└NonPlayerCharacter (5)
└Mob (1)