Approach
Relational aggregation
For Monthly Transactions II, 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
- 31 lines of SQL from the credited upstream file 1205.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 ApprovedTransactionsAndChargebacks AS (3 SELECT4 id,5 country,6 state,7 amount,8 DATE_FORMAT(trans_date, '%Y-%m') AS `month`9 FROM Transactions10 WHERE state = 'approved'11 UNION ALL12 SELECT13 trans_id AS id,14 country,15 'chargeback' AS state,16 amount,17 DATE_FORMAT(Chargebacks.trans_date, '%Y-%m') AS `month`18 FROM Chargebacks19 LEFT JOIN Transactions20 ON (Chargebacks.trans_id = Transactions.id)21 )22SELECT23 `month`,24 country,25 SUM(state = 'approved') AS approved_count,26 SUM(IF(state = 'approved', amount, 0)) AS approved_amount,27 SUM(state = 'chargeback') AS chargeback_count,28 SUM(IF(state = 'chargeback', amount, 0)) AS chargeback_amount29FROM ApprovedTransactionsAndChargebacks30GROUP BY 1, 2;31