通缉:用于计算满足特定条件的记录的SQL查询&返回有关最高计数的信息

时间:2018-01-06 05:38:44

标签: mysql sql

我有一个谜题...我有一个数据库表存储游戏的分数。它记录了玩家的名字,他们的计算机对手的名字,以及每个人的最终得分:

 player_name | bot_name | player_score | bot_score
---------------------------------------------------
  Alan         bot1          2            1
  Bill         bot1          3            0 
  Casey        bot2          5            0
  Alan         bot2          0            3
  Bill         bot3          1            2           
  Casey        bot3          4            0
  Alan         bot4          0            3

对于每个机器人,具有最大胜利率的玩家是具有最高(player_score - bot_score)值的玩家。我想编写一个SQL查询来查找具有最大胜利率的玩家。

示例:在上表中,Bill比bot1获得了最大的胜利,Casey在bot2和bot3上获得了最大的胜利,并且没有玩家获得比bot4更大的胜利,因为没有玩家赢得该僵尸。因此,比尔有一个最大的胜利,凯西有两个。在这种情况下,查询应返回“Casey”和“2”,因为那是胜利率最高的玩家。

是否可以编写单个SQL查询来检索此信息?

1 个答案:

答案 0 :(得分:1)

这很复杂。对于每个机器人,您可以通过以下方式获得具有最大边距的玩家(或多个玩家):

select bot_name, max(player_score - bot_score) as max_diff
from t
where player_score > bot_score
group by bot_name;

让得分最高的球员有点棘手:

select t.*
from t
where (t.player_score - t.bot_score) = 
       (select max(player_score - bot_score) as max_diff
        from t t2
        where t2.player_score > t2.bot_score and
              t2.bot_name = t.bot_name
       );

但是,这仍然不是你想要的。你想要拥有最大胜利的球员。以下是按顺序获取列表的方法:

select t.player_name, count(*) as num_wins
from t
where (t.player_score - t.bot_score) = 
       (select max(player_score - bot_score) as max_diff
        from t t2
        where t2.player_score > t2.bot_score and
              t2.bot_name = t.bot_name
       )
group by t.player_name
order by num_wins desc;