WITH team_stats AS (
SELECT
t.name as team_name,
COUNT(*) as matches_played,
SUM(CASE
WHEN (m.home_team_id = t.team_id AND m.home_score > m.away_score)
OR (m.away_team_id = t.team_id AND m.away_score > m.home_score)
OR (m.home_team_id = t.team_id AND m.home_penalty_score > m.away_penalty_score)
OR (m.away_team_id = t.team_id AND m.away_penalty_score > m.home_penalty_score)
OR (m.home_team_id = t.team_id AND m.home_extratime_score > m.away_extratime_score)
OR (m.away_team_id = t.team_id AND m.away_extratime_score > m.home_extratime_score)
THEN 1 ELSE 0 END) as wins,
SUM(CASE
WHEN m.home_team_id = t.team_id THEN m.away_score
WHEN m.away_team_id = t.team_id THEN m.home_score
ELSE 0 END) as goals_conceded
FROM @blt.ultimate_soccer_dataset.teams t
JOIN @blt.ultimate_soccer_dataset.matches m ON t.team_id = m.home_team_id OR t.team_id = m.away_team_id
JOIN @blt.ultimate_soccer_dataset.seasons s ON m.season_id = s.season_id
JOIN @blt.ultimate_soccer_dataset.competitions c ON s.competition_id = c.competition_id
WHERE c.name = 'FIFA Club World Cup'
AND m.status = 'Match Finished'
GROUP BY t.name
)
SELECT
team_name,
matches_played,
wins,
ROUND(wins * 100 / matches_played, 0) as win_percentage,
goals_conceded
FROM team_stats
ORDER BY win_percentage DESC
LIMIT 5