더보기
Table: Employee
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| empId | int |
| name | varchar |
| supervisor | int |
| salary | int |
+-------------+---------+
empId is the column with unique values for this table.
Each row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager.
Table: Bonus
+-------------+------+
| Column Name | Type |
+-------------+------+
| empId | int |
| bonus | int |
+-------------+------+
empId is the column of unique values for this table.
empId is a foreign key (reference column) to empId from the Employee table.
Each row of this table contains the id of an employee and their respective bonus.
Write a solution to report the name and bonus amount of each employee with a bonus less than 1000.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Employee table:
+-------+--------+------------+--------+
| empId | name | supervisor | salary |
+-------+--------+------------+--------+
| 3 | Brad | null | 4000 |
| 1 | John | 3 | 1000 |
| 2 | Dan | 3 | 2000 |
| 4 | Thomas | 3 | 4000 |
+-------+--------+------------+--------+
Bonus table:
+-------+-------+
| empId | bonus |
+-------+-------+
| 2 | 500 |
| 4 | 2000 |
+-------+-------+
Output:
+------+-------+
| name | bonus |
+------+-------+
| Brad | null |
| John | null |
| Dan | 500 |
+------+-------+
보너스가 1000 보다 작은 직원들의 이름과 보너스를 출력하시오.
최초 쿼리
SELECT
e.name,
b.bonus
FROM Employee as e
LEFT JOIN Bonus as b
ON e.empid = b.empid
WHERE b.bonus < 1000;
헷깔렸던 점
최초 시도에서 조건절에 b.bonus < 1000 을 하였으나 계속해서 오답!
그래서 조건절을 빼고 조인만 한 결과를 출력해보았더니, bonus에 null 값이 존재.
나의 시도
null값도 출력해야 되니, SELECT절에서 CASE WHEN 절 사용을 시도해봄.
CASE WHEN b.bonus < 1000 then b.bonus ELSE null END AS bonus결과는 계속해서 null값은 제외한 행들만 출력됨
심플하게 생각해보자! 조건절에서 뭔가 할 수 있을 것 같애!!
b.bonus가 1000 보다 큰 행들이거나 + b.bonus가 null인 행들이건 !!!
조건절을 이렇게 해볼까?
WHERE b.bonus < 1000 OR b.bonus is null;
✔️ 오케이!!!
LEFT JOIN을 하면 오른쪽 테이블에 없는 행들은 null값이 생김

생각해보면 bonus 가 null이라는 것은 받지 않은 것과 마찬가지니깐, 그 행들을 0 으로 처리해서 출력하라는 조건이 없는 이상은
null도 함께 보여주어야 함!
최종쿼리
SELECT
e.name,
b.bonus
FROM Employee as e
LEFT JOIN Bonus as b
ON e.empid = b.empid
WHERE b.bonus < 1000
OR b.bonus is null;
AND 아니고 OR로 null인 행도 함께 출력!
'SQL' 카테고리의 다른 글
| [SQL/코드카타] 모든 조합의 CROSS JOIN과 참여한 시험을 LEFT JOIN (0) | 2025.11.18 |
|---|---|
| [SQL/코드카타] Average Time of Process per Machine (0) | 2025.11.14 |
| [SQL/코드카타] 하루 전 보다 온도가 높은 데이터 값 찾기 (0) | 2025.10.30 |