[SQL]

LeetCode 코딩 테스트 - Customers Who Bought All Products(LV.Medium)

indongspace 2025. 3. 5. 20:22

 

 

Table: Customer

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| customer_id | int     |
| product_key | int     |
+-------------+---------+
This table may contain duplicates rows. 
customer_id is not NULL.
product_key is a foreign key (reference column) to Product table.

 

Table: Product

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_key | int     |
+-------------+---------+
product_key is the primary key (column with unique values) for this table.

 

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.

The result format is in the following example.

 

Example 1:

Input: 
Customer table:
+-------------+-------------+
| customer_id | product_key |
+-------------+-------------+
| 1           | 5           |
| 2           | 6           |
| 3           | 5           |
| 3           | 6           |
| 1           | 6           |
+-------------+-------------+
Product table:
+-------------+
| product_key |
+-------------+
| 5           |
| 6           |
+-------------+
Output: 
+-------------+
| customer_id |
+-------------+
| 1           |
| 3           |
+-------------+
Explanation: 
The customers who bought all the products (5 and 6) are customers with IDs 1 and 3.

 

테이블: Customer

컬럼명타입

customer_id int
product_key int
  • 이 테이블에는 중복된 행이 포함될 수 있습니다.
  • customer_id는 NULL이 아닙니다.
  • product_key는 Product 테이블의 참조 키(Foreign Key)입니다.

테이블: Product

컬럼명타입

product_key int
  • product_key는 이 테이블의 기본 키(Primary Key)로, 유일한 값을 가집니다.

문제:

Customer 테이블에서 Product 테이블의 모든 제품을 구매한 고객의 ID를 조회하는 SQL 쿼리를 작성하세요.

결과 테이블의 정렬 순서는 상관없습니다.


예제 입력 및 출력:

입력:

Customer 테이블:

customer_id product_key

1 5
2 6
3 5
3 6
1 6

Product 테이블:

product_key

5
6

출력:

customer_id

1
3

설명:

모든 제품(5, 6)을 구매한 고객은 customer_id = 1과 customer_id = 3입니다.

 

# 고객 별로 구매한 고유한 제품(DISTINCT)의 개수와, product 테이블의(고유한 행만 존재) 행 개수가 일치한다면, 모든 제품을 구매한 사람이라는 얘기다.
SELECT
    customer_id
FROM customer
GROUP BY
    customer_id
# 1. GROUP BY COUNT(DISTINCT)로 고객 별 구매한 고유제품 개수 / PRODUCT 테이블의 행 개수(=제품 개수) 구한다.
# 2. 조건을 걸어 두 개가 같은 고객 ID 만 추출
HAVING
    COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM product)