๐ป ๋ฌธ์ ์ฃผ์ : https://leetcode.com/problems/biggest-single-number/description/?envType=study-plan-v2&envId=top-sql-50
Biggest Single Number - LeetCode
Can you solve this real interview question? Biggest Single Number - Table: MyNumbers +-------------+------+ | Column Name | Type | +-------------+------+ | num | int | +-------------+------+ This table may contain duplicates (In other words, there is no pr
leetcode.com
๐ป ๋ฌธ์
A single number is a number that appeared only once in the MyNumbers table. Find the largest single number. If there's no single number, report null.
๐ป ์ฝ๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
select max(num) as num
from
(select num from MyNumbers group by num having count(num) = 1) as a
๐ป ๋ฌธ์ ํ์ด
์ด๋ฒ ๋ฌธ์ ๋ Easy ๋์ด๋์์์๋ ๊ฝค๋ ์ค๋ฅ๋ฅผ ๋ง์ด ๊ฒช์๋ ๋ฌธ์ ์๋ค. ์ด๋ ๋ฌธ์ ์กฐ๊ฑด์ธ max ๊ฐ ๋๋ null ๊ฐ์ ์ฒ๋ฆฌํ๋ ๊ณผ์ ์์ ๋ฐ์ํ๋ ์ด์๋ก, ์ฐจ๊ทผ์ฐจ๊ทผ ํ์ด ๊ณผ์ ์ ์ฎ๊น์ผ๋ก์จ ๋ฌธ์ ํ์ด๋ฅผ ๋ค์ ํ ๋ฒ ๋์๊ธฐ๊ณ ์ ํ๋ค.
1๏ธโฃ Single number : appeared only 1 time in the MyNumbers table
2๏ธโฃ Find the largest single number. If there's no single number, then report 'null'
1๏ธโฃ Single number ์ฐพ๊ธฐ
๋ฌธ์ ์์ Single number๋, MyNumbers๋ผ๋ ํ ์ด๋ธ์ ์ค์ง ํ ๋ฒ๋ง ์ ๋ ฅ๋์ด ์๋ ์ซ์๋ผ๊ณ ์ ์ํ๋ค. ๊ทธ๋ ๋ค๋ ๊ฒ์ ๊ฐ ์ซ์๋ณ๋ก ๋ช ๋ฒ ์ ๋ ฅ๋์ด ์๋์ง ๊ทธ ์๋ฅผ count()ํ๋ฉด ๋๋ค๋ ๋ป์ด๊ธฐ ๋๋ฌธ์ group by๊ฐ ํ์ํ๋ค๋ ๊ฒ์ ์ ์ ์๋ค.
select num from MyNumbers group by num having count(num) = 1
2๏ธโฃ Find the largest single number or 'null'
1๏ธโฃ๊น์ง ํ๋ฉด Single number์ ํด๋นํ๋ ์ซ์๋ค์ด ํํฐ๋ง๋์ด select์ ์ํด ์ถ์ถ๋ ์ ์๋ค. ํ์ง๋ง ์ฐ๋ฆฌ๋ ์ด์ค์์๋ '๊ฐ์ฅ ํฐ' single number์ ์ถ์ถํด์ผ ํ๋๋ฐ ๋ง์ฝ single number๊ฐ ์๋ค๋ฉด null์ ๋์ ์ถ๋ ฅํด์ผ ํ๋ค. ๋ง์ฝ ์ 1๏ธโฃ๋จ๊ณ์์ select์ ifnull ๋ฑ์ ์ฌ์ฉํ ๊ฒฝ์ฐ, ์ด๋ฏธ group by๋ฅผ ํตํด ์ง๊ณ๋ ๊ฒฐ๊ณผ๋ฌผ์์ having์ ์ ํตํด ํํฐ๋ง์ด ๋์๊ธฐ ๋๋ฌธ์ null์ธ ๊ฐ์ด ๋์ฌ ์๊ฐ ์๋ค (* case2).
๋ฐ๋ผ์ ์ฐ๋ฆฌ๋ 1๏ธโฃ์์ ์์ฑํ ์ฟผ๋ฆฌ๋ฅผ from ์ ์ ๋ค์ด๊ฐ ์๋ธ์ฟผ๋ฆฌ๋ก ์ฌ์ฉํ์ฌ, ์ด ์๋ธ์ฟผ๋ฆฌ ๋ด์์ single number๊ฐ ์์ผ๋ฉด ๊ทธ๊ฒ์ ์ถ๋ ฅํ๊ณ , ์์ผ๋ฉด ์๋์ผ๋ก null์ด ์ถ๋ ฅ๋๊ฒ ๋ง๋ค๋ฉด ๋๋ค.
select max(num)
from
(select num from MyNumbers group by num having count(num) = 1)
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SQL50] #29. Customers Who Bought All Products (1) | 2024.01.09 |
---|---|
[SQL50] #27. Find Followers Count (2) | 2024.01.06 |
[SQL50] #26. Classes More Than 5 Students (1) | 2024.01.05 |
[LeetCode][SQL50] #25. Product Sales Analysis III (1) | 2024.01.04 |
[LeetCode][SQL50] #24. User Activity for the Past 30 Days I (1) | 2024.01.04 |