LeetCode 1045. Customers Who Bought All Products SQL Solution
Problem
LeetCode SQL Problem
- Customers Who Bought All Products
Customer table
| customer_id | product_key |
|---|---|
| 1 | 5 |
| 2 | 6 |
| 3 | 5 |
| 3 | 6 |
| 1 | 6 |
Product table
| product_key |
|---|
| 5 |
| 6 |
Solution
- MySQL
- TSQL
Customers Who Bought All Products
SELECT C.customer_id
FROM Customer AS C
GROUP BY C.customer_id
-- Only show ids of customers who bought all the products
HAVING count(DISTINCT C.product_key) = (
-- Count all the products in the Product table
SELECT count(*)
FROM Product
)
Customers Who Bought All Products
SELECT C.customer_id
FROM Customer AS C
GROUP BY C.customer_id
-- Only show ids of customers who bought all the products
HAVING count(DISTINCT C.product_key) = (
-- Count all the products in the Product table
SELECT count(*)
FROM Product
)
Query Output
| customer_id |
|---|
| 1 |
| 3 |