๐ป ๋ฌธ์ ์ฃผ์ : Customers Who Bought All Products - LeetCode
Customers Who Bought All Products - LeetCode
Can you solve this real interview question? Customers Who Bought All Products - Table: Customer +-------------+---------+ | Column Name | Type | +-------------+---------+ | customer_id | int | | product_key | int | +-------------+---------+ This table may
leetcode.com
๐ป ๋ฌธ์
Write a solution to report the customer ids from the Customer table that bought all the products in the Product table. Return the result table in any order.
๐ป ์ฝ๋ ๋ฏธ๋ฆฌ๋ณด๊ธฐ
select customer_id
from Customer
group by customer_id
having count(distinct product_key) = (select count(product_key) from Product)
๐ป ๋ฌธ์ ํ์ด
๊ฐ์ธ์ ์ผ๋ก ์ด๋ฒ ๋ฌธ์ ๋ ๋ฌธ์ ๋ฅผ ํด์ํ๊ธฐ๋ณด๋ค๋ Example์ ๋ณด๊ณ ์๋ฆฌ๋ฅผ ํ์ ํ๋ ๊ฒ ๋ ์ฝ๋ค ๋๊ปด์ก๋ค.
์ฐ์ ์ฐ๋ฆฌ๋ ์๋ ๋ด์ฉ์ ๊ตฌํด์ผ ํ๋ค.
1๏ธโฃ Product table์ ์๋ ๋ชจ๋ Products
2๏ธโฃ 1๏ธโฃ์ ๊ตฌ๋งคํ ๋ชจ๋ Customer๋ค์ ID
1๏ธโฃ Product table์ ์๋ ๋ชจ๋ Products
๋ฌธ์ ์์ ๊ตฌํ๊ณ ์ ํ๋ ํต์ฌ์ '๋ชจ๋ Products๋ฅผ ๊ตฌ๋งคํ ๊ณ ๊ฐ๋ค์ ID ๋ฆฌ์คํธ'์ด๊ธฐ ๋๋ฌธ์ ๊ฐ ๊ณ ๊ฐ๋ค์ด ๊ตฌ๋งคํ ์ํ์ด Product ํ ์ด๋ธ ๋ชจ๋ ๋ ์ฝ๋๋ฅผ ์ถฉ์กฑํ๋๊ฐ๋ฅผ ๋ด์ผ ํ๋ค. ์ฆ, Product ํ ์ด๋ธ ๋ด product_key๋ ๊ณ ๊ฐ๋ค์ด ์ํ์ ์๋๊ฐ ์ฌ์ง ์์๋๊ฐ์ ๋ํ '์กฐ๊ฑด'์ด ๋๋ฏ๋ก where ์ ์ ๋ค์ด๊ฐ๊ฒ ๋๋ค.
select
from
where (product_key) in Product table
2๏ธโฃ 1๏ธโฃ์ ๊ตฌ๋งคํ ๋ชจ๋ Customer๋ค์ ID
๊ทธ๋ฆฌ๊ณ ์ด์ 2๏ธโฃ์ ์ Example Input&Output์ ๊ฐ์ด ์ดํด๋ณด๋๋ก ํ์.
customer_id | product_key |
1 | 5 |
2 | 6 |
3 | 5 |
3 | 6 |
1 | 6 |
Product_key๊ฐ 5, 6์ธ ์ํ๋ค ์ค ์ด ๋ชจ๋ ์ํ์ ๊ตฌ๋งคํ ๊ณ ๊ฐ์ 1, 3, ์ด ๋์ด๋ค. ์ฌ๊ธฐ์์ ํ ๊ฐ์ง ์ฃผ๋ชฉํด์ผ ํ ์ ์ ๊ฐ ๊ณ ๊ฐ๋ณ๋ก ํ ๊ฐ์ง ์ํ์ ํ ๋ฒ ์๊ฑด ๋ ๋ฒ ์๊ฑด ๊ฒฐ๊ตญ ๋ชจ๋ ์ํ์ ๊ตฌ๋งคํ ์๋์ ๊ฒฝ์ฐ, ์ด ๊ตฌ๋งคํ (๊ณ ์ ) ์ํ์ ์๋ Product ํ ์ด๋ธ ๋ด ๋ชจ๋ product_key ์์ ๊ฐ๋ค๋ ๊ฒ์ด๋ค. ์ด๊ฒ ๋ฐ๋ก ์ด๋ฒ ๋ฌธ์ ์ ํต์ฌ์ด๋ค.
์ฆ, ๋ค์ ๋งํด ๊ฐ ๊ณ ๊ฐ๋ณ๋ก group by function์ ํตํด ์ง๊ณํ๊ณ , ์ดํ ๊ฐ ๊ณ ๊ฐ์ด ๊ตฌ๋งคํ ์ด ์ํ์ ์๊ฐ Product ํ ์ด๋ธ์ ๋ชจ๋ product_key ์์ ๊ฐ๋ค๋ฉด ๊ทธ ๊ณ ๊ฐ์ ๋ชจ๋ ์ํ์ ๊ตฌ๋งคํ๋ค๊ณ ๋ณผ ์ ์๋ ๊ฒ์ด๋ค. ์ด๋ ์ฐ๋ฆฌ๋ group by function์ ์ธ ๊ฒ์ด๊ธฐ ๋๋ฌธ์ 1๏ธโฃ์์ ์๊ธฐํ '์กฐ๊ฑด'์ where์ด ์๋ having ์ ๋ก ๋ค์ด๊ฐ๊ฒ ๋๋ค.
select customer_id
from Customer
group by customer_id
having count(distinct product_key) = (select count(product_key) from Product)
'SQL > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[SQL50] #28. Biggest Single Number (1) | 2024.01.07 |
---|---|
[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 |