๐ป ๋ฌธ์ ์ฃผ์ : Find Customer Referee - LeetCode
Find Customer Referee - LeetCode
Can you solve this real interview question? Find Customer Referee - Table: Customer +-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | name | varchar | | referee_id | int | +-------------+---------+ In SQL, id is the
leetcode.com
๐ป ๋ฌธ์
Find the names of the customer that are not referred by the customer with 'id = 2'. Return the result table in any order.
- id๊ฐ 2์ธ ๊ณ ๊ฐ์๊ฒ ์ถ์ฒ๋ฐ์ง ์์ ๊ณ ๊ฐ ์ด๋ฆ์ ์ฐพ์ผ์์ค. ๊ฒฐ๊ณผ ํ ์ด๋ธ ์์๋ ์๊ด์์ต๋๋ค.
๐ป ์ฝ๋ ๋ฐ ํ์ด
select name
from Customer
where referee_id != 2 or isnull(referee_id) = 1 -- isnull(A) : A๊ฐ null ๊ฐ์ ๊ฐ์ง๋ฉด TRUE(1)
์ ๋ฌธ์ ๋ฅผ ๋ณด๋ฉด ์กฐ๊ฑด์ด ํ๋ ๊ฐ์ง๋ง ์๋ฐํ ๋งํ๋ฉด ๋ ๊ฐ์ ์กฐ๊ฑด์ ๊ฐ์ง๊ณ ์๋ค.
1๏ธโฃ ID๊ฐ 2์ธ ๊ณ ๊ฐ์ ์ ์ธํ ๊ณ ๊ฐ์๊ฒ ์ถ์ฒ ๋ฐ์ ๊ณ ๊ฐ์ผ ๊ฒ
2๏ธโฃ ๋๋ ์๋ฌด๋ฐ ๊ณ ๊ฐ์๊ฒ๋ ์ถ์ฒ ๋ฐ์ง ์์ ๊ณ ๊ฐ์ผ ๊ฒ
2๏ธโฃ ๋๋ ์๋ฌด๋ฐ ๊ณ ๊ฐ์๊ฒ๋ ์ถ์ฒ ๋ฐ์ง ์์ ๊ณ ๊ฐ์ผ ๊ฒ
๋ฌธ์ ๋ฅผ ๋ณด๋ฉด 1๏ธโฃ๋ง ์กฐ๊ฑด์ผ๋ก ๊ฑธ๋ฉด ๋ ๊ฒ ๊ฐ์ผ๋ Output ์์๋ฅผ ๋ณด๋ฉด referee_id๊ฐ null์ธ Will, Jane, ๊ทธ๋ฆฌ๊ณ Bill๋ ๊ฒฐ๊ณผ์ ์ถ๋ ฅ๋์ด ์๋ค. ์ฆ, referee_id๊ฐ 2๋ง ์๋๋ฉด ๋๋ค๋ ๋ป์ด๋ค.
๋ค๋ง where referee_id != 2๋ง where์ ์ ๋ฃ์ ๊ฒฝ์ฐ, null์ธ ๋ ์ฝ๋๋ ์ง๊ณ๋์ง ์๊ธฐ ๋๋ฌธ์ null์ ๊ฐ์ง๊ณ ์๋ ๋ ์ฝ๋๋ ํฌํจ๋ ์ ์๋๋ก ๋ฐ๋ก ์ฒดํฌ๋ฅผ ํด์ฃผ์ด์ผ ํ๋ค. ์ด๋ฅผ ์ํด isnull()์ด๋ผ๋ ํจ์๋ฅผ ์ผ๋ค.
isnull()์ ๋ง๊ทธ๋๋ก ๋งค๊ฐ๋ณ์๋ก ๋ค์ด๊ฐ ์ปฌ๋ผ์์ null์ธ ๋ ์ฝ๋๊ฐ ์์ผ๋ฉด 1์, ์์ผ๋ฉด 0์ ๋ฐํํ๋ค. ์ ์ฝ๋์์ ์ฐ๋ฆฌ๋ isnull(referee_id) = 1์ด๋ผ๊ณ ์กฐ๊ฑด์ ๊ฑธ์๊ธฐ ๋๋ฌธ์ null์ธ ๋ ์ฝ๋๋ where ์กฐ๊ฑด์ ์ถฉ์กฑ๋๋ฉด์ select ์ ์์ ๊ฐ์ด ์ถ๋ ฅ๋ ์ ์๊ฒ ๋๋ค.
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode][SQL50] #6. Replace Employee ID With The Unique Identifier (0) | 2023.11.07 |
---|---|
[LeetCode][SQL50] #5. Invalid Tweets (0) | 2023.11.06 |
[LeetCode][SQL50] #4. Article Views I (0) | 2023.11.06 |
[LeetCode][SQL50] #3. Big Countries (0) | 2023.11.06 |
[LeetCode][SQL50] #1. Recyclable and Low Fat Products (0) | 2023.11.03 |