|
| 1 | +/* |
| 2 | +Question 3521. Find Product Recommendation Pairs |
| 3 | +Link: https://leetcode.com/problems/find-product-recommendation-pairs/description/?envType=problem-list-v2&envId=database |
| 4 | +
|
| 5 | +Table: ProductPurchases |
| 6 | +
|
| 7 | ++-------------+------+ |
| 8 | +| Column Name | Type | |
| 9 | ++-------------+------+ |
| 10 | +| user_id | int | |
| 11 | +| product_id | int | |
| 12 | +| quantity | int | |
| 13 | ++-------------+------+ |
| 14 | +(user_id, product_id) is the unique key for this table. |
| 15 | +Each row represents a purchase of a product by a user in a specific quantity. |
| 16 | +Table: ProductInfo |
| 17 | +
|
| 18 | ++-------------+---------+ |
| 19 | +| Column Name | Type | |
| 20 | ++-------------+---------+ |
| 21 | +| product_id | int | |
| 22 | +| category | varchar | |
| 23 | +| price | decimal | |
| 24 | ++-------------+---------+ |
| 25 | +product_id is the primary key for this table. |
| 26 | +Each row assigns a category and price to a product. |
| 27 | +Amazon wants to implement the Customers who bought this also bought... feature based on co-purchase patterns. Write a solution to : |
| 28 | +
|
| 29 | +Identify distinct product pairs frequently purchased together by the same customers (where product1_id < product2_id) |
| 30 | +For each product pair, determine how many customers purchased both products |
| 31 | +A product pair is considered for recommendation if at least 3 different customers have purchased both products. |
| 32 | +
|
| 33 | +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. |
| 34 | +*/ |
| 35 | + |
| 36 | +SELECT |
| 37 | + p1.product_id AS product1_id, |
| 38 | + p2.product_id AS product2_id, |
| 39 | + p1.category AS product1_category, |
| 40 | + p2.category AS product2_category, |
| 41 | + COUNT(DISTINCT pp1.user_id) AS customer_count |
| 42 | +FROM ProductInfo AS p1 |
| 43 | +CROSS JOIN ProductInfo AS p2 |
| 44 | +RIGHT JOIN --noqa: CV08 |
| 45 | + ProductPurchases AS pp1 |
| 46 | + ON p1.product_id = pp1.product_id |
| 47 | +RIGHT JOIN --noqa: CV08 |
| 48 | + ProductPurchases AS pp2 |
| 49 | + ON p2.product_id = pp2.product_id AND pp1.user_id = pp2.user_id |
| 50 | +WHERE p1.product_id < p2.product_id |
| 51 | +GROUP BY p1.product_id, p2.product_id, p1.category, p2.category |
| 52 | +HAVING COUNT(DISTINCT pp1.user_id) >= 3 AND COUNT(DISTINCT pp2.user_id) >= 3 |
| 53 | +ORDER BY customer_count DESC, p1.product_id ASC, p2.product_id ASC |
0 commit comments