-
Notifications
You must be signed in to change notification settings - Fork 43
/
customers-who-bought-all-products.sql
82 lines (70 loc) · 1.81 KB
/
customers-who-bought-all-products.sql
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
https://code.dennyzhang.com/customers-who-bought-all-products
LeetCode: Customers Who Bought All Products
+-------------+---------+
| 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.
For 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.
*/
# V0
select customer_id
from Customer
group by customer_id
having count(distinct product_key) = (
select count(1)
from Product)
# V1
# https://code.dennyzhang.com/customers-who-bought-all-products
select customer_id
from Customer
group by customer_id
having count(distinct product_key) = (
select count(1)
from Product)
# V2
# Time: O(n + k), n is number of customer, k is number of product
# Space: O(n + k)
SELECT customer_id
FROM customer
GROUP BY customer_id
HAVING count(DISTINCT product_key)=
(SELECT count(DISTINCT product_key)
FROM product)
ORDER BY NULL