105번. Customers Who Bought All Products
(링크)
Write a solution to report the customer ids from the Customer table that bought all the products in the Product table.
이 문제는 product 테이블에 존재하는 모든 제품을 구매한 customer를 찾는 문제이다
정리하면, 모든 제품을 구매해야 한다 == product 테이블의 distinct count(*) 값만큼 구매하면 된다고 할 수 있다.
⇒ customer 테이블의 count(distinct product_key) == product 테이블의 distinct(*)인 customer_id를 찾으면 된다
WHERE절에 서브쿼리는 자주 썼지만, 이번엔 customer_id로 GROUP BY를 하고 거기에 조건을 걸 것이기 때문에 HAVING 절에 서브쿼리를 활용하기로 했다
SELECT
customer_id
# , count(distinct product_key) as 'cnt'
FROM
customer
GROUP BY
customer_id
HAVING
count(distinct product_key) = (SELECT count(distinct product_key) FROM product)
;
처음 이 문제를 풀었을 때는 불필요하게 WITH문을 2개나 사용했는데,
문제를 이해하고 나면 훨씬 짧고 간단하게 짤 수 있다
문제에서 요구하는 바가 무엇인지, 그것을 어떻게 얻어낼 수 있는지 떠올릴 수 있는 연습이 보다 필요할 듯.