Approach
Relational aggregation
For Number of Transactions per Visit, 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 1336.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 Users AS (3 SELECT4 Visits.user_id,5 Visits.visit_date,6 COUNT(Transactions.transaction_date) AS transaction_count7 FROM Visits8 LEFT JOIN Transactions9 ON (10 Visits.user_id = Transactions.user_id11 AND Visits.visit_date = Transactions.transaction_date)12 GROUP BY 1, 213 ),14 RowNumbers AS (15 SELECT ROW_NUMBER() OVER() AS `row_number`16 FROM Transactions17 UNION ALL18 SELECT 019 )20SELECT21 RowNumbers.`row_number` AS transactions_count,22 COUNT(Users.user_id) AS visits_count23FROM RowNumbers24LEFT JOIN Users25 ON (RowNumbers.`row_number` = Users.transaction_count)26WHERE RowNumbers.`row_number` <= (27 SELECT MAX(transaction_count) FROM Users28 )29GROUP BY 130ORDER BY 1;31