Skip to content
BytePatterns

Customers Who Bought Every Product

MediumSQL#group-by#having#count-distinct~20m

Problem

A shop keeps its catalogue in product(key) and every sale in purchase(customer_id, product_key). Every product_key in purchase exists in product, and a customer can buy the same product many times. Write a query that returns the customers who have bought every product in the catalogue at least once, as a single column customer_id, sorted.

Examples

Input:  product = [5, 6], purchase = [(1, 5), (2, 6), (3, 5), (3, 6), (1, 6)]
Output: [(1,), (3,)]
Why:    customers 1 and 3 bought both 5 and 6; customer 2 never bought 5
Input:  product = [5, 6, 7], purchase = [(1, 5), (1, 5), (1, 6), (2, 5), (2, 6), (2, 7)]
Output: [(2,)]
Why:    customer 1 has three rows but only two different products
Input:  product = [8], purchase = []
Output: []
Why:    edge case, nobody bought anything

Hints

0 / 3

Stuck on the idea rather than the code? Aggregations & GROUP BY covers it.