Approach
Relational aggregation
For Top Three Wineries, 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
- 36 lines of SQL from the credited upstream file 2991.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 WineryToTotalPoints AS (3 SELECT4 country,5 winery,6 SUM(points) AS total_points7 FROM Wineries8 GROUP BY 1, 29 ),10 RankedWineries AS (11 SELECT12 *,13 RANK() OVER(14 PARTITION BY country15 ORDER BY total_points DESC, winery16 ) AS `rank`17 FROM WineryToTotalPoints18 )19SELECT20 country,21 MAX(22 CASE WHEN `rank` = 1 THEN CONCAT(winery, ' (', total_points, ')') END23 ) AS top_winery,24 IFNULL(25 MAX(CASE WHEN `rank` = 2 THEN CONCAT(winery, ' (', total_points, ')') END),26 'No second winery'27 ) AS second_winery,28 IFNULL(29 MAX(CASE WHEN `rank` = 3 THEN CONCAT(winery, ' (', total_points, ')') END),30 'No third winery'31 ) AS third_winery32FROM RankedWineries33WHERE `rank` <= 334GROUP BY 135ORDER BY 1;36