Saya tidak memiliki latar belakang PostgreSQL tetapi mari kita lihat apakah ini berfungsi:
Saya akan memulai ini dengan menyederhanakannya, dengan menulis kueri yang terlebih dahulu mengembalikan skor total menurut pemain:
SELECT player_id, SUM(score) score
FROM (
SELECT first_player as player_id, first_score as score
FROM matches
UNION ALL
SELECT second_player, second_score
FROM matches
)
GROUP BY player_id
Sekarang, gabungkan kumpulan data itu ke pemain untuk menemukan grup:
SELECT w.player_id, p.group_id, w.score
FROM
(
SELECT player_id, SUM(score) score
FROM (
SELECT first_player as player_id, first_score as score
FROM matches
UNION ALL
SELECT second_player, second_score
FROM matches
)
GROUP BY player_id
) as w
inner join players p
on p.player_id = w.player_id
Sekarang kami memiliki semua pemain, skor total dan grup mereka. Kami ingin mengidentifikasi pemenang berdasarkan kelompok? Kita dapat menggunakan peringkat berfungsi untuk melakukan ini:
SELECT
w.player_id,
p.group_id,
w.score,
RANK() OVER (PARTITION BY p.group_id ORDER BY score DESC) as group_placement
FROM
(
SELECT player_id, SUM(score) score
FROM (
SELECT first_player as player_id, first_score as score
FROM matches
UNION ALL
SELECT second_player, second_score
FROM matches
)
GROUP BY player_id
) as w
inner join players p
on p.player_id = w.player_id
Sekarang kita tinggal memilih yang teratas di setiap grup (peringkat =1) menggunakan WHERE
SELECT
player_id,
group_id
FROM
(
SELECT
w.player_id,
p.group_id,
w.score,
RANK() OVER (PARTITION BY p.group_id ORDER BY score DESC) as group_placement
FROM
(
SELECT player_id, SUM(score) score
FROM (
SELECT first_player as player_id, first_score as score
FROM matches
UNION ALL
SELECT second_player, second_score
FROM matches
)
GROUP BY player_id
) as w
inner join players p
on p.player_id = w.player_id
) as gp
WHERE group_placement = 1
Terlihat rumit? ya, tetapi Anda dapat melihat hasil akhir disediakan sedikit demi sedikit. Setiap langkah ini adalah 'subtabel' dan Anda dapat menjalankan dan mengamati data di setiap titik.