본문 바로가기
SQL/코딩테스트

[leetcode / MySQL] 1045. Customers Who Bought All Products

by Hi_heidi 2024. 1. 30.

문제

💡 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(*) FROM Product)

 

해설

SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product)
  • Product(p)테이블의 모든 제품을 구매한 고객을 출력하는 문제다. 고객별로 구매한 고유한 제품 수를 테이블p의 개수와 비교하여 문제를 해결할 수 있다.
  • 먼저 Customer(c)테이블을 고객 customer_id로 그룹화한다.
  • 이후 HAVING절에서 product_key의 고윳값 개수를 센 숫자가 테이블p의 전체 제품 개수를 센 숫자와 같은 그룹만 필터링한다. 메인쿼리에서는 테이블c만 사용하는데 테이블p의 전체 제품 개수를 세야 하므로 HAVING절 서브쿼리를 사용해 구해주었다. 테이블c에는 중복이 있을 수 있기 때문에 DISTINCT를, 테이블p의 product_key는 주식별자(PK)라 중복이 없기 때문에 COUNT(*)로 세 주었다.
  • 이후 SELECT문에서 조건을 만족하는 customer_id를 출력한다.