Først skal du få den samlede score for hver spiller og derefter slutte dig til players
.
Brug derefter vinduesfunktionen FIRST_VALUE() for at få den bedste spiller i hver gruppe:
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
Se demoen .