O desafio pedia para listar as top 3 vinícolas de cada país com seus pontos, preenchendo mensagens quando não houver vinícola suficiente.


Example 1

Input:
Wineries table:
+-----+-----------+--------+-----------------+
| id  | country   | points | winery          |
+-----+-----------+--------+-----------------+
| 103 | Australia | 84     | WhisperingPines |
| 737 | Australia | 85     | GrapesGalore    |
| 848 | Australia | 100    | HarmonyHill     |
| 222 | Hungary   | 60     | MoonlitCellars  |
| 116 | USA       | 47     | RoyalVines      |
| 124 | USA       | 45     | Eagle'sNest     |
| 648 | India     | 69     | SunsetVines     |
| 894 | USA       | 39     | RoyalVines      |
| 677 | USA       | 9      | PacificCrest    |
+-----+-----------+--------+-----------------+

Output:
+-----------+---------------------+-------------------+----------------------+
| country   | top_winery          | second_winery     | third_winery         |
+-----------+---------------------+-------------------+----------------------+
| Australia | HarmonyHill (100)   | GrapesGalore (85) | WhisperingPines (84) |
| Hungary   | MoonlitCellars (60) | No second winery  | No third winery      |
| India     | SunsetVines (69)    | No second winery  | No third winery      |
| USA       | RoyalVines (86)     | Eagle'sNest (45)  | PacificCrest (9)     |
+-----------+---------------------+-------------------+----------------------+


Solução SQL

SELECT
    country,
    MAX(CASE WHEN rn = 1 THEN winery || ' (' || total_points || ')' END) as top_winery,
    COALESCE(MAX(CASE WHEN rn = 2 THEN winery || ' (' || total_points || ')' END), 'No second winery') as second_winery,
    COALESCE(MAX(CASE WHEN rn = 3 THEN winery || ' (' || total_points || ')' END), 'No third winery') as third_winery
FROM (
    SELECT
        country,
        winery,
        SUM(points) AS total_points,
        ROW_NUMBER() OVER (
            PARTITION BY country
            ORDER BY SUM(points) DESC, winery ASC
        ) AS rn
    FROM Wineries
    GROUP BY country, winery
) t
WHERE rn <= 3
GROUP BY country
ORDER BY country ASC;


A solução implementada foi a seguinte:

  1. Agregação por país e vinícola
  2. Classificação com ROW_NUMBER()
  3. Filtragem das três primeiras vinícolas
  4. Formatação e tratamento de casos sem segunda ou terceira vinícola
  5. Agrupamento final e ordenação por país