Approach
Relational aggregation
For Customer Purchasing Behavior Analysis, 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
- 37 lines of SQL from the credited upstream file 3230.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 RankedCategoriesPerCustomer AS (3 SELECT4 Transactions.customer_id,5 Products.category,6 RANK() OVER(7 PARTITION BY Transactions.customer_id8 ORDER BY COUNT(Products.category) DESC,9 MAX(Transactions.transaction_date) DESC10 ) AS `rank`11 FROM Transactions12 INNER JOIN Products13 USING (product_id)14 GROUP BY 1, 215 ),16 TransactionsMetadata AS (17 SELECT18 Transactions.customer_id,19 ROUND(SUM(Transactions.amount), 2) AS total_amount,20 COUNT(Transactions.transaction_id) AS transaction_count,21 COUNT(DISTINCT Products.category) AS unique_categories,22 ROUND(AVG(Transactions.amount), 2) AS avg_transaction_amount,23 RankedCategoriesPerCustomer.category AS top_category24 FROM Transactions25 INNER JOIN Products26 USING (product_id)27 INNER JOIN RankedCategoriesPerCustomer28 USING (customer_id)29 WHERE RankedCategoriesPerCustomer.`rank` = 130 GROUP BY 131 )32SELECT33 *,34 ROUND(transaction_count * 10 + total_amount / 100, 2) AS loyalty_score35FROM TransactionsMetadata36ORDER BY loyalty_score DESC, customer_id;37