我有一张用户表,其中包含游戏每个级别的得分:
id | user_id | level | score 1 | David | 1 | 20 2 | John | 1 | 40 3 | John | 2 | 30 4 | Mark | 1 | 60 5 | David | 2 | 10 6 | David | 3 | 80 7 | Mark | 2 | 20 8 | John | 3 | 70 9 | David | 4 | 50 10 | John | 4 | 30
得分最高的每个级别需要获得什么SQL查询?
结果应为:
id | user_id | level | score 4 | Mark | 1 | 60 3 | John | 2 | 30 6 | David | 3 | 80 9 | David | 4 | 50
谢谢
如果您想建立联系,则可以执行以下操作:
select s.* from scores s where s.score = (select max(s2.score) from scores s2 where s2.level = s.level);
通过汇总以下内容,您可以在每个级别获得一行:
select s.level, s.score, group_concat(s.user_id) from scores s where s.score = (select max(s2.score) from scores s2 where s2.level = s.level) group by s.level, s.score;
这会将用户(如果有多个)组合到一个字段中。