|
| 1 | +/* |
| 2 | +Question 3554. Find Category Recommendation Pairs |
| 3 | +Link: https://leetcode.com/problems/find-category-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 identifier 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 unique identifier for this table. |
| 26 | +Each row assigns a category and price to a product. |
| 27 | +Amazon wants to understand shopping patterns across product categories. Write a solution to: |
| 28 | +
|
| 29 | +Find all category pairs (where category1 < category2) |
| 30 | +For each category pair, determine the number of unique customers who purchased products from both categories |
| 31 | +A category pair is considered reportable if at least 3 different customers have purchased products from both categories. |
| 32 | +
|
| 33 | +Return the result table of reportable category pairs ordered by customer_count in descending order, and in case of a tie, by category1 in ascending order lexicographically, and then by category2 in ascending order. |
| 34 | +*/ |
| 35 | + |
| 36 | +SELECT |
| 37 | + p1.category AS category1, |
| 38 | + p2.category AS category2, |
| 39 | + COUNT(DISTINCT pp2.user_id) AS customer_count |
| 40 | +FROM ProductInfo AS p1 |
| 41 | +CROSS JOIN ProductInfo AS p2 |
| 42 | +RIGHT JOIN --noqa: CV08 |
| 43 | + ProductPurchases AS pp1 |
| 44 | + ON p1.product_id = pp1.product_id |
| 45 | +RIGHT JOIN --noqa: CV08 |
| 46 | + ProductPurchases AS pp2 |
| 47 | + ON p2.product_id = pp2.product_id AND pp1.user_id = pp2.user_id |
| 48 | +WHERE p1.category < p2.category |
| 49 | +GROUP BY p1.category, p2.category |
| 50 | +HAVING COUNT(DISTINCT pp2.user_id) >= 3 |
| 51 | +ORDER BY customer_count DESC, p1.category ASC, p2.category ASC |
0 commit comments