๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
SQL/LeetCode

[LeetCode][SQL50] #2. Find Customer Referee

by ์ด๋ฎด 2023. 11. 3.
728x90

๐Ÿ’ป ๋ฌธ์ œ ์ฃผ์†Œ : 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์ธ ๊ณ ๊ฐ์—๊ฒŒ ์ถ”์ฒœ๋ฐ›์ง€ ์•Š์€ ๊ณ ๊ฐ ์ด๋ฆ„์„ ์ฐพ์œผ์‹œ์˜ค. ๊ฒฐ๊ณผ ํ…Œ์ด๋ธ” ์ˆœ์„œ๋Š” ์ƒ๊ด€์—†์Šต๋‹ˆ๋‹ค.

 

Input๊ณผ Output ์˜ˆ์‹œ

 

๐Ÿ’ป ์ฝ”๋“œ ๋ฐ ํ’€์ด

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 ์ ˆ์—์„œ ๊ฐ™์ด ์ถœ๋ ฅ๋  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•

'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