* Problem
Employees can belong to multiple departments. When the employee joins other departments, they need to decide which department is their primary department. Note that when an employee belongs to only one department, their primary column is 'N'.
Write a solution to report all the employees with their primary department. For employees who belong to one department, report their only department.
Return the result table in any order.
Input:
Employee table:
+-------------+---------------+--------------+
| employee_id | department_id | primary_flag |
+-------------+---------------+--------------+
| 1 | 1 | N |
| 2 | 1 | Y |
| 2 | 2 | N |
| 3 | 3 | N |
| 4 | 2 | N |
| 4 | 3 | Y |
| 4 | 4 | N |
+-------------+---------------+--------------+
Output:
+-------------+---------------+
| employee_id | department_id |
+-------------+---------------+
| 1 | 1 |
| 2 | 1 |
| 3 | 3 |
| 4 | 3 |
+-------------+---------------+
* Explanation
- The Primary department for employee 1 is 1.
- The Primary department for employee 2 is 1.
- The Primary department for employee 3 is 3.
- The Primary department for employee 4 is 3.
* Solution(Success)
select employee_id,department_id
FROM Employee
where (employee_id, primary_flag ) in
(SELECT employee_id,max(primary_flag )
FROM Employee
GROUP BY employee_id
)
'Study - Problems(IT) > LeetCode - SQL' 카테고리의 다른 글
1164. Product Price at a Given Date (0) | 2025.02.17 |
---|---|
180. Consecutive Numbers (0) | 2025.02.16 |
1731. The Number of Employees Which Report to Each Employee (0) | 2024.11.27 |
1045.Customers Who Bought All Products (0) | 2024.11.26 |
619.Biggest Single Number (0) | 2024.11.25 |