[SQL]

LeetCode 코딩 테스트 - Managers with at Least 5 Direct Reports(LV.Medium)

indongspace 2025. 3. 17. 20:38

 

 

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, name
# 쿼리 계산 방법 : 1. managerid에 5번 이상 등장하는 id추출 -> 2. 조건문으로 그 id를 가진 name 추출 
# 데이터의 기간 : x
# 사용할 테이블 : employee
# JOIN KEY : manager_id, id
# 데이터 특징 : x
SELECT
    name
FROM employee
# 2
WHERE
    id IN 
 ( # 1
    SELECT
        managerid
    FROM employee
    GROUP BY
        managerid
    HAVING
        COUNT(*) >= 5)