SQL/문제풀이

[LeetCode] primary-department-for-each-employee

응엉잉 2024. 3. 9. 12:10

https://leetcode.com/problems/primary-department-for-each-employee/?envType=study-plan-v2&envId=top-sql-50

-- department가 1개
(SELECT employee_id,
    department_id
FROM employee
WHERE employee_id IN (
    SELECT employee_id
    FROM employee
    GROUP BY employee_id
    HAVING COUNT(DISTINCT department_id) = 1)
)

UNION

-- department가 2개
(SELECT employee_id,
    department_id
FROM employee
WHERE employee_id IN (
    SELECT employee_id
    FROM employee
    GROUP BY employee_id
    HAVING COUNT(DISTINCT department_id) > 1)
    AND primary_flag = 'Y')

내가 작성한 쿼리는 다음과 같다.

department가 1개인 employee 따로, 2개인 employee 따로 employee_id, department_id를 구한 후 UION하는 방식!

-- department가 2개
SELECT employee_id, department_id
FROM Employee 
WHERE primary_flag = 'Y' -- primary_flag가 Y인 경우에 대해서만

UNION

-- department가 1개
SELECT employee_id, department_id
FROM Employee
GROUP BY employee_id
HAVING COUNT(employee_id) = 1

ORDER BY employee_id

방식은 동일하지만 이렇게 짜는게 훨씬 간단하다 !