[MySQL] 1873. Calculate Special Bonus

2022. 11. 27. 13:50TIL💡/Database

https://leetcode.com/problems/calculate-special-bonus/?envType=study-plan&id=sql-i 

 

Calculate Special Bonus - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

풀이 방식은 크게 2가지가 있다.

1. UNION

2. CASE WHEN THEN

 

UNION의 경우에는 보너스가 있는 경우와 없는 경우를 합한다.

SELECT employee_id, salary as bonus
FROM employees
WHERE employee_id % 2 <> 0 AND name NOT LIKE 'M%'

UNION

SELECT employee_id, 0 as bonus
FROM employees
WHERE employee_id % 2 = 0 OR name LIKE 'M%'
ORDER BY employee_id

그리고 CASE문을 쓰는 경우는 아래와 같이 하면 ELSE 문과 같이 쓰면 된다.

SELECT employee_id, 
    CASE WHEN employee_id % 2 = 1 AND name NOT LIKE 'M%' THEN salary 
    ELSE 0 
    END
    AS bonus
FROM Employees
ORDER BY employee_id