MySQL查询提取每个玩家的记分板数据

时间:2014-11-11 09:27:54

标签: mysql

我有一个包含以下字段的MySQL表:

  • user_id(每位用户唯一)
  • user_name
  • level(1-4)
  • score

此表用于存储4个等级的游戏的分数。玩家可以根据需要多次玩各个级别。完成一个级别后,会在数据库中添加一个新行。

我需要编写一个SQL查询,在该表中搜索玩家的user_iduser_name,以及每个级别的最高得分总和。结果必须按sum(score)的降序排序。

3 个答案:

答案 0 :(得分:0)

SELECT user_id, user_name, sum(maxscore) as overallscore
FROM
    -- subquery to get only the maximum scores
    (SELECT user_id,user_name,level,max(score) as maxscore 
    FROM your_table
    GROUP BY  user_id,user_name,level) as maximums -- don't know if MYSQL requires alias
GROUP BY user_id,user_name 
ORDER BY sum(maxscore) DESC

答案 1 :(得分:0)

这是一种方法:

select
  user_id, 
  user_name, 
  sum(score) as total_score
from (
    select 
      user_id, 
      user_name, 
      level, 
      max(score) as score 
    from t
    group by user_id, user_name, level
) max_level_scores
group by user_id, user_name
order by total_score desc

Sample SQL Fiddle

答案 2 :(得分:0)

以下是使用SQLite实现的表格版本:

sqlite> create table scoreboard(user_name string, level integer, score integer);
sqlite> insert into scoreboard values("bob", 1, 100);
sqlite> insert into scoreboard values("bob", 1, 50);
sqlite> insert into scoreboard values("bob", 2, 200);
sqlite> insert into scoreboard values("bob", 3, 20);
sqlite> insert into scoreboard values("ted", 4, 200);

要获得每个玩家/等级的最高分,您需要执行以下操作:

SELECT user_name, level, MAX(score) FROM scoreboard GROUP BY user_name, level;

结果:

bob|1|100
bob|2|200
bob|3|20
ted|4|200

然后,您可以根据玩家名称对这些结果进行分组:

SELECT user_name, SUM(hiscore) AS totalscore FROM
(
    SELECT user_name, MAX(score) AS hiscore
    FROM scoreboard
    GROUP BY user_name, level
) GROUP BY user_name ORDER BY totalscore DESC;

结果:

bob|320
ted|200

我不确定您为什么会有单独的user_nameuser_id列,因为只需要其中一列来唯一标识玩家。假设您不仅限于一个表,则可以修改上面的代码,将user_name字段替换为user_id列,对于单独的“播放器”,这将是foreign key名称“表格:

playernames

1|bob
2|ted
3|steve
4|james

记分板

1|1|100
1|1|50
1|2|200
1|3|20
2|4|200