Approach
Relational aggregation
For Find Category Recommendation Pairs, the query transforms and combines relational rows, then filters or aggregates them into the requested result.
- Identify the source rows and join keys.
- Apply filters before aggregation when possible.
- Group, rank, or project the final columns required by the result.
Code notes
- 42 lines of SQL from the credited upstream file 3554.sql.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Review join cardinality, grouping keys, and available indexes when estimating query cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1WITH2 UserCategories AS (3 SELECT DISTINCT4 ProductPurchases.user_id,5 ProductInfo.category6 FROM ProductPurchases7 INNER JOIN ProductInfo8 USING (product_id)9 ),10 CategoryPairs AS (11 SELECT12 UserCategories.user_id,13 LEAST(14 UserCategories.category,15 UserCategories2.category16 ) AS category1,17 GREATEST(18 UserCategories.category,19 UserCategories2.category20 ) AS category221 FROM UserCategories22 INNER JOIN UserCategories AS UserCategories223 ON (24 UserCategories.user_id = UserCategories2.user_id25 AND UserCategories.category < UserCategories2.category)26 ),27 PairCustomerCounts AS (28 SELECT29 category1,30 category2,31 COUNT(DISTINCT user_id) AS customer_count32 FROM CategoryPairs33 GROUP BY 1, 234 )35SELECT36 category1,37 category2,38 customer_count39FROM PairCustomerCounts40WHERE customer_count >= 341ORDER BY customer_count DESC, category1, category2;42