인프런- 데이터 분석을 위한 고급 SQL: 섹션3 - 서브쿼리 Department Highest Salary 문제풀이(틀림/완전한 이해X)

르네·2023년 9월 26일
0

SQL

목록 보기
26/63

인프런 강의 <데이터 분석을 위한 고급 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

이렇게 했더니 결과값이 다음과 같이 나왔다.

idnamesalarydepartmentIdidname
1Joe7000011IT
2Jim9000011IT
3Henry8000022Sales
4Sam6000022Sales
5Max9000011IT

여기서 어떻게 손을 대야할지 모르겠다... 아직 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

배운점

  • INNER JOIN절에서 ON 'A' AND 'B' 형식으로도 쓸 수 있음.
  • FROM절에 서브쿼리 쓸 수 있으니까, FROM ~ INNER JOIN절에서도 서브쿼리 쓸 수 있음.
  • 첫번째 INNER JOIN문에서 ~ 'ON e.departmentid = dh.departmentid'만 하면 전체 직원의 salary가 다 나온다. 가장 높은 급여를 추출해야 하니까 'AND e.salary = dh.max_salary'도 INNER JOIN문에 넣어주면, 각 부서별로 가장 높은 급여를 받는 직원들의 리스트가 나온다.
  • GROUP BY, INNER JOIN이 함께 나오는 문제는 최대한 많이 풀어보고 익숙해지자!
profile
데이터분석 공부로그

0개의 댓글