-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path3521. Find Product Recommendation Pairs.sql
More file actions
53 lines (47 loc) · 2.07 KB
/
3521. Find Product Recommendation Pairs.sql
File metadata and controls
53 lines (47 loc) · 2.07 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Question 3521. Find Product Recommendation Pairs
Link: https://leetcode.com/problems/find-product-recommendation-pairs/description/?envType=problem-list-v2&envId=database
Table: ProductPurchases
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id | int |
| product_id | int |
| quantity | int |
+-------------+------+
(user_id, product_id) is the unique key for this table.
Each row represents a purchase of a product by a user in a specific quantity.
Table: ProductInfo
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| category | varchar |
| price | decimal |
+-------------+---------+
product_id is the primary key for this table.
Each row assigns a category and price to a product.
Amazon wants to implement the Customers who bought this also bought... feature based on co-purchase patterns. Write a solution to :
Identify distinct product pairs frequently purchased together by the same customers (where product1_id < product2_id)
For each product pair, determine how many customers purchased both products
A product pair is considered for recommendation if at least 3 different customers have purchased both products.
Return the result table ordered by customer_count in descending order, and in case of a tie, by product1_id in ascending order, and then by product2_id in ascending order.
*/
SELECT
p1.product_id AS product1_id,
p2.product_id AS product2_id,
p1.category AS product1_category,
p2.category AS product2_category,
COUNT(DISTINCT pp1.user_id) AS customer_count
FROM ProductInfo AS p1
CROSS JOIN ProductInfo AS p2
RIGHT JOIN --noqa: CV08
ProductPurchases AS pp1
ON p1.product_id = pp1.product_id
RIGHT JOIN --noqa: CV08
ProductPurchases AS pp2
ON p2.product_id = pp2.product_id AND pp1.user_id = pp2.user_id
WHERE p1.product_id < p2.product_id
GROUP BY p1.product_id, p2.product_id, p1.category, p2.category
HAVING COUNT(DISTINCT pp1.user_id) >= 3 AND COUNT(DISTINCT pp2.user_id) >= 3
ORDER BY customer_count DESC, p1.product_id ASC, p2.product_id ASC