2015-04-14 79 views
0

我有一個記分牌,顯示基於大多數平均得分的當前排名。SQL子查詢聚合錯誤

我和6位朋友每晚打幾回合。

我們跟蹤: Playername(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是前年一輪tournamentid。

但是它沒有正確計算上一輪的平均值,而是取最後一輪的平均值。

結果:

enter image description here

,你可以在這裏看到的avg_last是錯誤的。這裏練成例如其中數字是從哪裏來的:

enter image description here

任何線索如何正確的代碼?嘗試過OVER(),但不支持MariaDB。

回答

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) 
+0

謝謝!那完美的工作! – Jorn