[LeetCode] 570. Managers with at Least 5 Direct Reports - SQL

Donghyun·2024년 8월 16일
0

Code Kata - SQL

목록 보기
41/61
post-thumbnail

링크: https://leetcode.com/problems/managers-with-at-least-5-direct-reports/

Table: Employee

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
| department  | varchar |
| managerId   | int     |
+-------------+---------+
id is the primary key (column with unique values) for this table.
Each row of this table indicates the name of an employee, their department, and the id of their manager.
If managerId is null, then the employee does not have a manager.
No employee will be the manager of themself.

Write a solution to find managers with at least five direct reports.

Return the result table in any order.

The result format is in the following example.

Example 1:

Input:
Employee table:
+-----+-------+------------+-----------+
| id  | name  | department | managerId |
+-----+-------+------------+-----------+
| 101 | John  | A          | null      |
| 102 | Dan   | A          | 101       |
| 103 | James | A          | 101       |
| 104 | Amy   | A          | 101       |
| 105 | Anne  | A          | 101       |
| 106 | Ron   | B          | 101       |
+-----+-------+------------+-----------+
Output:
+------+
| name |
+------+
| John |
+------+

문제풀이

목표: 5명 이상의 직속 부하가 있는 매니저를 찾는 솔루션을 작성

  • managerId 가 null 인 사람이 매니저이다.

최종코드

SELECT e1.name
FROM Employee e1
    JOIN Employee e2
    ON e1.id = e2.managerId
GROUP BY e2.managerId
HAVING COUNT(*) >= 5;

설명

이 문제는 셀프조인을 활용해 풀었다.

  • Employee 테이블을 셀프조인을 사용해 둘로 나눈다.
    • 매니저의 역할을 하는 e1 테이블과
    • e1이 매니저인 직원들을 나타내는 e2 테이블
  • 이후 e2 테이블의 managerId 를 기준으로 GROUP BY 하고,
  • HAVING 절을 통해 각 매니저가 관리하는 직원들의 수가 5명 이상인 경우만 포함하도록 필터링
  • 마지막으로 매니저의 이름을 SELECT
profile
데이터분석 공부 일기~!

0개의 댓글