选择每个玩家的总分

时间:2019-04-12 07:24:06

标签: mysql sql

假定简单的分数表(player_id,分数)。如何为每个玩家选择得分总和?并将结果olny限制为N个最高和。

player_id|score
---------------
      457|   20
      457|   25
      300|   50
      300|    5
      100|    1

如果N为2,则结果应为

player_id|score
---------------
      300|   55
      457|   45

3 个答案:

答案 0 :(得分:2)

首先,您需要对结果进行分组,然后按分组结果进行排序,并将结果限制为2条记录(我假设使用players表名):

select player_id, sum(score) score
from players
group by player_id
order by score desc
limit 2

Demo

答案 1 :(得分:0)

SELECT TOP 2 player_id, SUM(score) FROM score GROUP BY player_id

答案 2 :(得分:0)

您可以使用sum()group by和

对于mysql,您可以使用limit

  select player_id, sum(score) score
  from my_table 
  group by player_id 
  order by score desc
  limit 2 

对于SqlServer,您可以使用TOP 2

  select TOP 2 player_id, sum(score) score
  from my_table 
  order by score desc
  group by player_id