Approach
Relational aggregation
For Total Sales Amount by Year, 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
- 27 lines of SQL from the credited upstream file 1384.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 Calendar AS (3 # We should be given a calendar in hand. Otherwise, assume we are oracle4 # and already know the testcase.5 SELECT '2018' AS year, '2018-01-01' AS start, '2018-12-31' AS end6 UNION ALL7 SELECT '2019' AS year, '2019-01-01' AS start, '2019-12-31' AS end8 UNION ALL9 SELECT '2020' AS year, '2020-01-01' AS start, '2020-12-31' AS end10 )11SELECT12 Product.product_id,13 Product.product_name,14 Calendar.year AS report_year,15 (16 DATEDIFF(17 LEAST(Sales.period_end, Calendar.end),18 GREATEST(Sales.period_start, Calendar.start)19 ) + 120 ) * Sales.average_daily_sales AS total_amount21FROM Sales22INNER JOIN Calendar23 ON (Calendar.year BETWEEN YEAR(Sales.period_start) AND year(Sales.period_end))24INNER JOIN Product25 USING (product_id)26ORDER BY 1, 3;27