我有一个记分牌,根据获得的大多数平均分数显示当前排名。
我和6个朋友每晚都会玩几轮。我们追踪: 玩家名称(playerid) 点(轮次累积的所有点数的总和) 轮次(打了多少轮) 平均积分(积分/轮次)
这样可行,但我想添加一个计算,如果玩家在记分牌中上升或下降以及平均点数。
这是我的代码:
SELECT t1.playerid as player
,SUM(t1.points) AS points
,count(t1.playerid) AS rounds
,avg(t1.points) as average_points
/* get tournament ID of last round */
,(select distinct(tournamentid) from pokermax_scores order by tournamentid desc limit 1,1) as 1_round_ago
/* calculate average points earned one round ago */
,(select avg(points) from pokermax_scores where tournamentid <= 1_round_ago group by t1.playerid) as avg_last
,(avg(t1.points)-(select avg(points) from pokermax_scores where tournamentid <= 1_round_ago group by t1.playerid)) as gain_loss
FROM pokermax_scores as t1
GROUP BY player
ORDER BY average_points DESC
1_round_ago是最后一轮的巡回赛。
然而,它没有正确计算最后一轮的平均值,而是采用上一轮平均值的平均值。
结果:
正如你在这里看到的那样,avg_last是错误的。这里有数字来自的例子:
有任何线索如何纠正代码?尝试了OVER()但MariaDB不支持。
答案 0 :(得分:0)
您需要使用相关子查询来获取行中玩家的平均值。变化:
(select avg(points)
from pokermax_scores
where tournamentid <= 1_round_ago
group by t1.playerid)
为:
(select avg(points)
from pokermax_scores t2
where tournamentid <= 1_round_ago
and t2.playerid = t1.playerid)