Eerst moet je de totale score van elke speler krijgen en dan lid worden van players
.
Gebruik vervolgens de FIRST_VALUE() vensterfunctie om de topspeler van elke groep te krijgen:
SELECT DISTINCT p.group_id,
FIRST_VALUE(p.player_id) OVER (PARTITION BY p.group_id ORDER BY m.score DESC) winner_id
FROM players p
LEFT JOIN (
SELECT player, SUM(score) score
FROM (
SELECT match_id, first_player player, first_score score FROM matches
UNION ALL
SELECT match_id, second_player, second_score FROM matches
) t
GROUP BY player
) m ON m.player = p.player_id
Bekijk de demo .