-- 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
방식은 동일하지만 이렇게 짜는게 훨씬 간단하다 !
'SQL > 문제풀이' 카테고리의 다른 글
[LeetCode] count-salary-categories (0) | 2024.03.09 |
---|---|
[LeetCode] product-price-at-a-given-date 📌 (0) | 2024.03.09 |
[LeetCode] immediate-food-delivery-ii (0) | 2024.03.05 |
[LeetCode] average-selling-price 📌 (0) | 2024.03.05 |
[LeetCode] monthly-transactions (0) | 2024.03.04 |