-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomers Who Bought All Products.sql
More file actions
39 lines (35 loc) · 1.34 KB
/
Customers Who Bought All Products.sql
File metadata and controls
39 lines (35 loc) · 1.34 KB
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
-- Problem Statement:
-- Return the IDs of customers who have purchased every product listed in the
-- Product table. A customer qualifies if the set of product_key values they
-- bought matches the complete set of product_key values present in Product.
-- Table Layouts
-- -------------------------------------------------------------------
-- Table: Customer
-- +-------------+---------+
-- | Column Name | Type |
-- +-------------+---------+
-- | customer_id | int | -- NOT NULL
-- | product_key | int | -- FK → Product.product_key
-- +-------------+---------+
-- (The table may contain duplicate rows.)
-- Table: Product
-- +-------------+---------+
-- | Column Name | Type |
-- +-------------+---------+
-- | product_key | int | -- Primary key
-- +-------------+---------+
-- Approach:
-- 1. Count how many distinct products exist overall:
-- SELECT COUNT(DISTINCT product_key) FROM Product
-- 2. For each customer, count how many distinct product_key values they have
-- purchased (GROUP BY customer_id).
-- 3. Keep only those customers whose distinct-product count equals the total
-- number of products. Those customers bought everything.
-- SQL Solution:
SELECT
customer_id
FROM Customer
GROUP BY customer_id
HAVING COUNT(DISTINCT product_key) = (
SELECT COUNT(DISTINCT product_key) FROM Product
);