2015-11-07 62 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