Customers Who Bought All Products Problem
Description
LeetCode Problem 1045.
Table: Customer
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| customer_id | int |
| product_key | int |
+-------------+---------+
product_key is a foreign key to Product table.
Table: Product
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_key | int |
+-------------+---------+
product_key is the primary key column for this table.
Write an SQL query for a report that provides the customer ids from the Customer table that bought all the products in the Product table.
Return the result table in any order.
The query result format is in the following example:
Customer table:
+-------------+-------------+
| customer_id | product_key |
+-------------+-------------+
| 1 | 5 |
| 2 | 6 |
| 3 | 5 |
| 3 | 6 |
| 1 | 6 |
+-------------+-------------+
Product table:
+-------------+
| product_key |
+-------------+
| 5 |
| 6 |
+-------------+
Result table:
+-------------+
| customer_id |
+-------------+
| 1 |
| 3 |
+-------------+
The customers who bought all the products (5 and 6) are customers with id 1 and 3.
Solution
Approach: Count Distinct Products per Customer
A customer bought every product exactly when the number of different products they bought equals the number of products in Product.
GROUP BY customer_idandCOUNT(DISTINCT product_key)gives the number of different products per customer.(SELECT COUNT(*) FROM Product)gives the total.product_keyis the primary key ofProduct, soCOUNT(*)counts each product once.HAVINGkeeps the customers whose two counts are equal.
DISTINCT matters because Customer has no primary key and can repeat a purchase. Customer 4 in the test data bought product 5 twice: COUNT(product_key) would be 2 and wrongly match the 2 products, while COUNT(DISTINCT product_key) is 1. Since product_key is a foreign key to Product, a customer cannot have bought a product that isn't in it, so equal counts mean the same set.
The Pandas version counts unique products per customer with nunique() and keeps those equal to len(product).
SELECT customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (SELECT COUNT(*) FROM Product);