在阅读了其他几个类似问题的答案后,我仍然无法完成以下任务:
有一个球员得分列表,我想得到每个球员的最高 n 得分(得分表只有玩家ID和值)。最终目的是使用AVG()
函数汇总分数。
另请注意, n 界限只是一个限制;玩家可能具有小于 n 分数,在这种情况下,所有这些分数都应该被计算出来。
计算结果后,加入播放器表将允许将每个玩家ID扩展为可打印信息。
答案 0 :(得分:2)
在MySQL中,您需要vars来满足您的要求:
select
idplayer, Score
from
(
select
idplayer, T.Score,
@r := IF(@g=idplayer,@r+1,1) RowNum,
@g := idplayer
from (select @g:=null) initvars
CROSS JOIN
(
SELECT s.Score,
s.idplayer
FROM scores s
ORDER BY idplayer, s.score DESC
) T
) U
WHERE RowNum <= 3
create table scores( idplayer int, score int);
insert into scores values
(1,5), (1,7), (1,18), (1,27), (2,6);
结果:
| IDPLAYER | SCORE |
--------------------
| 1 | 27 |
| 1 | 18 |
| 1 | 7 |
| 2 | 6 |
答案 1 :(得分:1)
从这里开始:
drop table if exists scores;
create table scores (playerid integer, score integer);
insert into scores values
(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),
(2,1),(2,2),(2,3),(2,4);
select p1.playerid, p1.score
from scores p1, scores p2
where p1.playerid = p2.playerid
and
p1.score >=
ifnull((select score
from scores
where playerid=p1.playerid
order by score desc limit 4,1
),0)
group by p1.playerid,p1.score;
将为您提供所需的最高分数列表。
答案 2 :(得分:0)
我不是100%肯定这会在mysql中运行。但是,以下内容将该想法捕获为相关子查询:
select p.*,
(select sum(score)
from (select score
from scores s
where s.playerid = p.playerid
order by score desc
limit 5
) s2
) as summax5
from players p