๋ฌธ์
https://leetcode.com/problems/customers-who-bought-all-products/description/
์ฝ๋
๋์ ๋ต์
select customer_id
from customer
group by 1
having group_concat(product_key separator ',') in
(select group_concat(product_key separator ',')
from product)
ํ ๋ธ๋ก๊ทธ ๋ต์
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
๋ฌธ์ ํ์ด
ํ ๋ธ๋ก๊ทธ ๋ต์์ product ํ ์ด๋ธ์ product_key์ ๊ณ ์ ํ ๊ฐ์์
customer ํ ์ด๋ธ์ customer์ product_key์ ๊ณ ์ ํ ๊ฐ์๋ฅผ ๋น๊ตํ๋ ๋ฐฉ์์ผ๋ก ๋ฌธ์ ๋ฅผ ํผ ๊ฒ ๊ฐ๋ค.
๊ทผ๋ฐ ๊ณ ๊ฐ์ด ๋ง์ฝ 5, 6์ด ์๋ 5, 7์ ๋ณด์ ํ๊ณ ์์ผ๋ฉด ์ด ๋ฐฉ๋ฒ์ผ๋ก๋ ํ ์ ์๊ฒ ๋๋ค.
๋๋ ๊ฐ์๋ฟ๋ง ์๋๋ผ ์ซ์ ์์ฒด๋ฅผ ๋น๊ตํ๊ณ ์ถ์ด์ group_concat์ด๋ผ๋ ๋ฐฉ๋ฒ์ ์ฌ์ฉํ๋ค.
sql์์๋ ๋ค์ค๊ฐ๊ณผ ๋ค์ค๊ฐ์ ๋น๊ตํ ์ ์๋ ๋ฐฉ๋ฒ์ ์๋ ๊ฒ ๊ฐ์์
group_concat์ ์ฌ์ฉํด์ ๋ค์ค๊ฐ์ ๋จ์ผ๊ฐ์ผ๋ก ๋ณํํด์ฃผ์๋ค.
- group_concat( (distinct) ์ปฌ๋ผ separator '๊ตฌ๋ถ์' )
์์ ํจ์๋ฅผ ์ฌ์ฉํ๋ฉด groupingํ ๊ฒฐ๊ณผ๋ฅผ ํ์ค๋ก ์ถ๋ ฅํ ์ ์๊ฒ ๋ค. (groupingํ ๊ฒฐ๊ณผ๊ฐ ์๋์ฌ๋ ํฉ์ณ์ฃผ๋ ๋ฏ?)
distinct๋ฅผ ์ฌ์ฉํ๋ฉด ์ค๋ณต๊ฐ์ ์ ๊ฑฐํ ์ ์๊ฒ ๋ค.
๋๋ ์
๋์ ํ์ด ๋ฐฉ๋ฒ์ ์ด ๋ฌธ์ ์์๋ ๋ถํ์ํ๊ธฐ ๋๋ฌธ์
์๊ฐ์ด ๊ธ๋ฐํ sql ํ ์คํธ์์๋ ํ ๋ธ๋ก๊ทธ ํ์ด ๋ฐฉ๋ฒ์ผ๋ก ํธ๋ ๊ฒ ํ๋ช ํ ์ ์๊ฒ ๋ค.

'Tools > - SQL' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [SQL] solvesql | ์คํ ๋์ ๋ฌ ์๊ฐ ์ฐพ๊ธฐ (0) | 2025.02.09 |
|---|---|
| [SQL] leetcode | 1393. Capital Gain/Loss ์์ ํ์ด (0) | 2025.02.01 |
| [SQL] leetcode | 1204. Last Person to Fit in the Bus ์์ ํ์ด (0) | 2025.02.01 |
| [SQL] Leetcode | 1907. Count Salary Categories ์์ ํ์ด (0) | 2025.02.01 |
| [SQL] leetcode | 1164. Product Price at a Given Date ์์ ํ์ด (0) | 2025.01.24 |