Customers Who Bought All Products
Task: Write a solution to report the customer ids from the Customer table that bought all the products in the Product table.
Table: Customer
| Column Name | Type |
|---|---|
| customer_id | INT |
| product_key | INT |
Table: Product
| Column Name | Type |
|---|---|
| product_key | INT |
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 |
View Reference Solution & Explanation ▼
This solution uses the `GROUP BY` clause to aggregate results, a `HAVING` clause to filter the aggregated groups, and a subquery as a derived table or inline value.
SELECT customer_id FROM Customer GROUP BY customer_id HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product);