2015-11-07 59 views
1

的列和AVG之間的差異和我有一個包含用戶的成績,對於一個遊戲的表:MySQL查詢得到的同一列

UserID (Integer) 
MatchId (Integer) 
Score (Double) 

我想的getter和每個用戶的「分數高於平均水平」(PAA) - 用戶得分高於或低於平均水平的數量。

所以你需要計算「分數」平均每個「MatchId」, 然後在表中每一行計算,通過該 「分數」從比賽平均不同的金額。然後通過 用戶將該PAA值相加。

是否有可能通過MySQL查詢做到這一點?或者我需要PHP嗎?如果可以通過查詢完成,該查詢將是什麼樣子?

+0

什麼樣的遊戲包括浮點值?即使體操使得帶有小數做 – Strawberry

+0

你應該表現出你的第一次嘗試也 –

回答

1

計劃

  • 通過匹配
  • 計算平均得分加入用戶分數平均分數和由用戶ID

計算衍生差字段的總和設置

create table scores 
(
    UserID integer not null, 
    MatchId integer not null, 
    Score decimal(5, 2) not null, 
    primary key (UserID, MatchId) 
); 

insert into scores 
(UserID, MatchId, Score) 
values 
(1, 1, 22.1), 
(2, 1, 36.0), 
(3, 1, 35.3), 
(1, 2, 50.0), 
(2, 2, 39.8), 
(3, 2, 42.0) 
; 

查詢

select s.UserID, sum(s.Score - avgs.avg_score) as paa 
from scores s 
inner join 
(
select MatchId, avg(Score) as avg_score 
from scores 
group by MatchId 
) avgs 
on s.MatchId = avgs.MatchId 
group by s.UserID 
; 

輸出

+--------+-----------+ 
| UserID | paa | 
+--------+-----------+ 
|  1 | -2.966666 | 
|  2 | 0.733334 | 
|  3 | 2.233334 | 
+--------+-----------+ 

sqlfiddle

+0

看到:https://dev.mysql.com/doc/refman/5.5/en/from-clause-subqueries.html – VolkerK