인프런 강의 <데이터 분석을 위한 고급 SQL>을 듣고, 중요한 점을 정리한 글입니다.
Table: Employee
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| id | int |
| name | varchar |
| salary | int |
| departmentId | int |
+--------------+---------+
id is the primary key (column with unique values) for this table.
departmentId is a foreign key (reference columns) of the ID from the Department table.
Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.
Table: Department
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table. It is guaranteed that department name is not NULL.
Each row of this table indicates the ID of a department and its name.
Write a solution to find employees who have the highest salary in each of the departments.
Return the result table in any order.
The result format is in the following example.
SELECT *
FROM Employee AS S1
INNER JOIN Department AS S2 ON S1.departmentId = S2.Id
이렇게 했더니 결과값이 다음과 같이 나왔다.
id | name | salary | departmentId | id | name |
---|---|---|---|---|---|
1 | Joe | 70000 | 1 | 1 | IT |
2 | Jim | 90000 | 1 | 1 | IT |
3 | Henry | 80000 | 2 | 2 | Sales |
4 | Sam | 60000 | 2 | 2 | Sales |
5 | Max | 90000 | 1 | 1 | IT |
여기서 어떻게 손을 대야할지 모르겠다... 아직 GROUP BY 개념에 혼동이 있어 문제를 어떻게 구현해야 할지 감이 안 온다.
SELECT d.name AS department
, e.name AS employee
, e.salary
FROM Employee AS e
INNER JOIN (
SELECT DepartmentID, MAX(salary) AS max_salary
FROM Employee
GROUP BY DepartmentID
) AS dh ON e.departmentid = dh.departmentid
AND e.salary = dh.max_salary
INNER JOIN department AS d ON d.id = e.departmentid