Approach
Relational aggregation
For User Purchase Platform, 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
- 33 lines of SQL from the credited upstream file 1127.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 UserToAmount AS (3 SELECT4 user_id,5 spend_date,6 CASE7 WHEN COUNT(DISTINCT platform) = 2 THEN 'both'8 ELSE platform9 END AS platform,10 SUM(amount) AS amount11 FROM Spending12 GROUP BY 1, 213 ),14 DateAndPlatforms AS (15 SELECT DISTINCT(spend_date), 'desktop' AS platform16 FROM Spending17 UNION ALL18 SELECT DISTINCT(spend_date), 'mobile' AS platform19 FROM Spending20 UNION ALL21 SELECT DISTINCT(spend_date), 'both' AS platform22 FROM Spending23 )24SELECT25 DateAndPlatforms.spend_date,26 DateAndPlatforms.platform,27 IFNULL(SUM(UserToAmount.amount), 0) AS total_amount,28 COUNT(DISTINCT UserToAmount.user_id) AS total_users29FROM DateAndPlatforms30LEFT JOIN UserToAmount31 USING (spend_date, platform)32GROUP BY 1, 2;33