Mysql 使用排名求和(所有玩家所有回合的最佳 x 分数)

Mysql Sum using ranking (best x scores from all rounds for all players)

  1. 请帮忙。我在这个论坛上测试了很多例子都没有成功。

此脚本运行良好,但我现在希望将总分限制为最佳 14 轮。

SELECT 
RoundScoreCard.idPlayerDetails as ID,
#concat(PlayerFirstName," ",PlayerLastName)as Name,
sum(RoundScoreCardPlayerPoints) as Total 

from RoundScoreCard 

join PlayerDetails on RoundScoreCard.idPlayerDetails = PlayerDetails.idplayerdetails 
group by RoundScoreCard.idPlayerDetails 
order by Total DESC 

使用这个单个子查询进行测试工作正常;

select sum(RoundScoreCardPlayerPoints) 
FROM 
(select RoundScoreCardPlayerPoints
from RoundScoreCard
where RoundScoreCard.idPlayerDetails = @player 
order by RoundScoreCardPlayerPoints desc 
limit 14) as subquery
;

我已经为修改我能找到的每个示例而奋斗了大约一个星期,但就是无法让它列出所有玩家。我可以展示多种尝试,但这会使其他人混淆这个问题。 (我确实有一个使用记录测试然后使用 IF 语句的解决方案,但它似乎过多且时间成本高。)

  1. 还有;出于兴趣,是否可以有多个限制语句?也就是说,如果我只想要前 3 名球员在所有回合中获得最好的 14 个成绩怎么办?

示例http://sqlfiddle.com/#!9/f393a6/3

新的一年万事如意


好的 - 所以我在这篇文章的帮助下又进步了一点; https://www.databasejournal.com/features/mysql/selecting-the-top-n-results-by-group-in-mysql.html

谢谢Rob Gravelle

将每个玩家的最高分限制为 2

我的Sql现在是这样的:

Select idRoundScorecard, RoundScoreCardPlayerPoints,idPlayerDetails
 FROM
 (
   SELECT idRoundScorecard, RoundScoreCardPlayerPoints, idPlayerDetails,
   @player_score_rank := IF(@current_player = idPlayerDetails, 
                         @player_score_rank + 1, 
                         1
                      ) AS player_score_rank,
   @current_player := idPlayerDetails
   FROM RoundScoreCard
    ORDER BY idPlayerDetails, RoundScoreCardPlayerPoints DESC
 ) ranked
 WHERE player_score_rank <= 2;

现在又要求和排名了?

这是我的解决方案http://sqlfiddle.com/#!9/4f4fe7/9

select idPlayerDetails as ID, concat(PlayerFirstName," ",PlayerLastName)as Name,sum(Points) as Points
from
(Select idRoundScorecard, RoundScoreCardPlayerPoints as Points,idPlayerDetails
 FROM
 (SELECT idRoundScorecard, RoundScoreCardPlayerPoints, idPlayerDetails,
   @player_rank := IF(@current_player = idPlayerDetails, 
                         @player_rank + 1, 
                         1
                      ) AS player_rank,
   @current_player := idPlayerDetails
   FROM RoundScoreCard
    ORDER BY idPlayerDetails, RoundScoreCardPlayerPoints DESC
 ) ranked
 WHERE player_rank <= 5 )summed
natural join PlayerDetails
group by idPlayerDetails
order by Points desc
 ;

我错了 rank(),它需要 row_number()


With scores as (
  SELEct
RoundScoreCard.idPlayerDetails as ID,
RoundScoreCardPlayerPoints As pts,
Dense_rank() Over (Partition by idPlayerDetails
            Order by RoundScoreCardPlayerPoints  Desc) As rK,
Row_number() Over (Partition by idPlayerDetails
            Order by RoundScoreCardPlayerPoints  Desc) As rn
from RoundScoreCard 
)
select id, sum(pts) from scores
Where rn < 3
group by id;

给出最好的两轮总和。

db fiddle