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.
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) |
+-----------+---------------------+-------------------+----------------------+
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;
SUM(points)
) e agrupamos por country
e winery
.PARTITION BY country
), atribuimos um número de linha (ROW_NUMBER()
) ordenando pelo total de pontos em ordem decrescente.winery ASC
).rn <= 3
para considerar as top 3.CASE
para mostrar winery (total_points)
para as posições existentes.COALESCE
para substituir valores nulos por 'No second winery'
ou 'No third winery'
quando não houver vinículas suficientes.country
e ordenamos o resultado final em ordem crescente de país (ORDER BY country ASC
).