반응형
매니저는 다른 직원들의 managerId로 등장합니다. 즉, managerId를 기준으로 그룹화해서 해당 값을 가진 사람이 몇 명의 직원을 관리하는지 세면 됩니다.
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 |
+------+
Employee 테이블을 자기 자신과 조인하는데, e1.id = e2.managerId를 기준으로 매니저와 부하를 연결합니다.
SELECT * FROM Employee e1 JOIN Employee e2 ON e1.id = e2.managerId;
| id | name | department | managerId | id | name | department | managerId |
| --- | ---- | ---------- | --------- | --- | ----- | ---------- | --------- |
| 101 | John | A | null | 102 | Dan | A | 101 |
| 101 | John | A | null | 103 | James | A | 101 |
| 101 | John | A | null | 104 | Amy | A | 101 |
| 101 | John | A | null | 105 | Anne | A | 101 |
| 101 | John | A | null | 106 | Ron | B | 101 |
SELECT e1.name FROM Employee e1 JOIN Employee e2 ON e1.id = e2.managerId
GROUP BY e1.id
HAVING COUNT(*) >= 5;
- 매니저 ID로 그룹핑하고, 부하 수가 5명 이상인 매니저만 필터링
- 최종적으로 매니저 이름(e1.name) 출력
반응형
'Computer Science > SQL' 카테고리의 다른 글
SQL | LeetCode 1251. 날짜 범위 매핑으로 평균 판매가 구하기 (0) | 2025.05.06 |
---|---|
SQL | LeetCode 1934. 사용자 확인률 계산하기 (LEFT JOIN과 COALESCE, AVG()의 조합) (0) | 2025.05.05 |
SQL | LeetCode 1280. Nested Join (1) | 2025.05.04 |
SQL | LeetCode 1661. Self Join + GROUP BY (3) | 2025.05.03 |
SQL | LeetCode 197. 셀프 조인(Self Join)과 DATE_ADD를 활용한 날짜 비교 문제 (0) | 2025.05.02 |