[LeetCode/SQL] 1789. Primary Department for Each Employee

Sooyeon·2023년 11월 15일
0

문제풀이 

목록 보기
62/95
post-thumbnail

[LeetCode/SQL]


📌 1789. Primary Department for Each Employee

문제

풀이

-  employee_id별 primary_flag='N'인 department_id 출력하기 
=> department_id가 1개이면, 그대로 출력
=> department_id가 2개면,flag N 필터

방법

UNION사용

SELECT employee_id, department_id 
FROM Employee
WHERE primary_flag = 'Y'
UNION
SELECT employee_id, department_id 
FROM Employee 
GROUP BY employee_id
HAVING COUNT(employee_id) = 1

방법

SUBQUERY사용

SELECT DISTINCT employee_id, department_id
FROM Employee
WHERE employee_id IN (
    SELECT employee_id
    FROM Employee
    GROUP BY employee_id
    HAVING COUNT(*) = 1
  )
  OR primary_flag = 'Y'
ORDER BY employee_id;

0개의 댓글