Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 9bc4c67

Browse files
Create 1045-customers_who_bought_all_products.sql
1 parent 630967d commit 9bc4c67

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
-- 1045 - Customers who bought all products
2+
3+
-- Table: Customer
4+
5+
-- +-------------+---------+
6+
-- | Column Name | Type |
7+
-- +-------------+---------+
8+
-- | customer_id | int |
9+
-- | product_key | int |
10+
-- +-------------+---------+
11+
12+
-- This table may contain duplicates rows.
13+
-- customer_id is not NULL.
14+
-- product_key is a foreign key (reference column) to Product table.
15+
16+
17+
-- Table: Product
18+
19+
-- +-------------+---------+
20+
-- | Column Name | Type |
21+
-- +-------------+---------+
22+
-- | product_key | int |
23+
-- +-------------+---------+
24+
25+
-- product_key is the primary key (column with unique values) for this table.
26+
27+
-- Write a solution to report the customer ids from the Customer table that bought all the products in the Product table.
28+
29+
-- Return the result table in any order.
30+
31+
-- The result format is in the following example.
32+
33+
34+
35+
-- Example 1:
36+
37+
-- Input:
38+
-- Customer table:
39+
-- +-------------+-------------+
40+
-- | customer_id | product_key |
41+
-- +-------------+-------------+
42+
-- | 1 | 5 |
43+
-- | 2 | 6 |
44+
-- | 3 | 5 |
45+
-- | 3 | 6 |
46+
-- | 1 | 6 |
47+
-- +-------------+-------------+
48+
49+
-- Product table:
50+
-- +-------------+
51+
-- | product_key |
52+
-- +-------------+
53+
-- | 5 |
54+
-- | 6 |
55+
-- +-------------+
56+
57+
-- Output:
58+
-- +-------------+
59+
-- | customer_id |
60+
-- +-------------+
61+
-- | 1 |
62+
-- | 3 |
63+
-- +-------------+
64+
65+
-- Explanation:
66+
-- The customers who bought all the products (5 and 6) are customers with IDs 1 and 3.
67+
68+
69+
SELECT
70+
customer_id
71+
FROM
72+
Customer
73+
GROUP BY
74+
customer_id
75+
HAVING
76+
COUNT(distinct product_key) = (SELECT COUNT(product_key) FROM Product)
77+
;
78+
79+
-- OR
80+
81+
SELECT
82+
customer_id
83+
FROM
84+
(SELECT
85+
customer_id,
86+
COUNT(DISTINCT product_key) AS total_unique_products
87+
FROM
88+
Customer
89+
GROUP BY
90+
customer_id) c
91+
JOIN
92+
(SELECT COUNT(*) AS total FROM Product AS total) p
93+
WHERE c.total_unique_products = p.total
94+
;

0 commit comments

Comments
 (0)