Problem solution · SQL

Top Three Wineries

Top Three Wineries: a SQL solution using relational aggregation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Relational aggregation
Source
walkccc LeetCode Solutions
Length
36 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Relational aggregation

For Top Three Wineries, the query transforms and combines relational rows, then filters or aggregates them into the requested result.

  1. Identify the source rows and join keys.
  2. Apply filters before aggregation when possible.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeTop Three Wineries · SQLSQL
Use this to learn the idea, then write your own version.
WITH  WineryToTotalPoints AS (    SELECT      country,      winery,      SUM(points) AS total_points    FROM Wineries    GROUP BY 1, 2  ),  RankedWineries AS (    SELECT      *,      RANK() OVER(        PARTITION BY country        ORDER BY total_points DESC, winery      ) AS `rank`    FROM WineryToTotalPoints  )SELECT  country,  MAX(    CASE WHEN `rank` = 1 THEN CONCAT(winery, ' (', total_points, ')') END  ) AS top_winery,  IFNULL(    MAX(CASE WHEN `rank` = 2 THEN CONCAT(winery, ' (', total_points, ')') END),    'No second winery'  ) AS second_winery,  IFNULL(    MAX(CASE WHEN `rank` = 3 THEN CONCAT(winery, ' (', total_points, ')') END),    'No third winery'  ) AS third_wineryFROM RankedWineriesWHERE `rank` <= 3GROUP BY 1ORDER BY 1; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗