Customers Who Bought All Products Problem


Description

LeetCode Problem 1045.

Table: Customer

1
2
3
4
5
6
7
+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| customer_id | int     |
| product_key | int     |
+-------------+---------+
product_key is a foreign key to Product table.

Table: Product

1
2
3
4
5
6
+-------------+---------+
| 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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.


MySQL Solution

1
2
3
4
5
select customer_id
from Customer
group by customer_id
having count(distinct product_key) = 
    (select count(distinct product_key) from Product)




Related Posts

Exchange Seats Problem

LeetCode 626. Mary is a teacher in a middle school...

Customers Who Bought All Products Problem

LeetCode 1045. Write an SQL query for a report that...

Biggest Single Number Problem

LeetCode 619. Table my_numbers contains many numbers in column num...

Not Boring Movies Problem

LeetCode 620. X city opened a new cinema, many people...

Swap Salary Problem

LeetCode 627. Given a table salary, such as the one...

Actors And Directors Who Cooperated At Least Three Times Problem

LeetCode 1050. Write a SQL query for a report that...