MySQL按胜率排序(%)

时间:2016-01-05 17:21:34

标签: mysql

我的表格包含以下信息:

Player_ID | isWinner

其中PlayerID是玩家的ID,isWinner是布尔值(0表示输,1表示赢)。

相同Player_ID可以分为多行。

我的目标是进行查询以获取玩家订购的此表中的所有信息,从最高赢率(%)到最低赢率。

数据示例:

(Player_ID | isWinner)
1 | 1
1 | 1
1 | 1
2 | 0
2 | 0
2 | 1
3 | 0
3 | 0
3 | 0

查询将以这种方式对此数据进行排序:

  • 1 | 100% - >玩家ID 1的获胜率最高
  • 2 | 33% - >玩家ID 2具有第二赢率
  • 3 | 0% - >玩家ID 3的赢率最低

我可能需要按player_id分组并以某种方式计算每个玩家SUM的{​​{1}},然后将其除以记录的数量。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

此查询将返回每位玩家的平均值:

select player_id, avg(isWinner) as avg_is_winner
from players
group by player_id

然后你可以使用这个子查询加入你的表:

select players.*
from
  players inner join (
    select player_id, avg(isWinner) as avg_is_winner
    from players
    group by player_id
  ) c on players.player_id = c.player_id
order by
  avg_is_winner desc,
  isWinner desc

请查看小提琴here

答案 1 :(得分:1)

您可以使用avg()查找每位玩家的总胜场平均数,然后乘以100乘以百分比

select
    player_id as pid,
  avg(is_winner) * 100 as win_rate,
    (
        SELECT
            count(player_id)
        FROM
            `34617596`
        WHERE
            is_winner = 1
        AND player_id = pid
    ) AS total_wins
FROM
    `34617596`
group by pid
order by win_rate desc

请参阅小提琴: http://sqlfiddle.com/#!9/10f797/1

enter image description here