sql - 获得团队对所有其他团队的胜率

时间:2016-05-20 21:46:21

标签: sql postgresql

我希望能够计算出每个玩家对单个敌方玩家的胜率(并返回胜利百分比)。所以说敌方玩家是'104'。我想找出我的球员'23'对'104','48'对'104'等的胜率,以及他们总共玩了多少场比赛(以获得胜率) 我一直试图弄清楚如何在PostgreSQL中进行查询以执行以下操作:

输入:Matchups winner_team_id | winner_player_id | loser_team_id | loser_player_id ----------------+------------------+---------------+----------------- 26691960 | 24 | 45631137 | 104 26691960 | 23 | 45334612 | 104 26691960 | 48 | 22191174 | 104 26691960 | 23 | 31191882 | 104 26691960 | 14 | 20731636 | 104 26691960 | 14 | 23648001 | 104 26691960 | 14 | 35009401 | 104 26691960 | 23 | 28954626 | 104 28809466 | 104 | 26691960 | 23 70012915 | 104 | 26691960 | 24 ...

表:

player_id | win_rate | games_played
----------------------------------
23          75%        4
14          100%       3
48          100%       1
24          50%        4

(此表仅显示敌方玩家ID为104且团队中所有玩家ID = 26691960的游戏)

输出:

{{1}}

1 个答案:

答案 0 :(得分:1)

一些简单的聚合函数与FULL JOIN配对应该可以解决问题。请注意,COALESCE可能存在性能问题。您可以将COALESCE(win_count, 0) + COALESCE(loss_count, 0)包装在子查询中以获取games_played,然后在win_rate等式中使用它。

无论如何,不​​用多说:

SELECT COALESCE(wins.loser_player_id, losses.winner_player_id) as player_id,
(COALESCE(loss_count, 0) / (COALESCE(win_count, 0) + COALESCE(loss_count, 0)))::numeric(3, 2) as win_rate,
(COALESCE(win_count, 0) + COALESCE(loss_count, 0))::bigint as games_played

FROM (
    SELECT winner_player_id, loser_player_id, count(*) * 1::numeric(3,2) as win_count --this is a hack to get a decimal
    FROM a.scores win
    WHERE winner_player_id = 104
    GROUP BY winner_player_id, loser_player_id
)
as wins

FULL JOIN
(
    SELECT winner_player_id, loser_player_id, count(*) * 1::numeric(3,2) as loss_count
    FROM a.scores win
    WHERE loser_player_id = 104
    GROUP BY winner_player_id, loser_player_id
) as losses ON row(wins.winner_player_id, wins.loser_player_id) = row(losses.loser_player_id, losses.winner_player_id)