简体   繁体   English

MySQL查询以获取列和同一列的AVG之差

[英]MySQL query to get sum of differences between column and AVG of same column

I have a table which contains the scores by user, for a game: 我有一个表格,其中包含游戏的用户得分:

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

I'd like to getter sum each user's "points above average" (PAA) - the amount by which a user's score was above or below the average. 我想对每个用户的“高于平均分”(PAA)求和-用户得分高于或低于平均分的数量。

So you'd need to calculate the average of 'Score' for each 'MatchId', then for each row in the table calculate the amount by which the 'Score' differs from the match average. 因此,您需要为每个“ MatchId”计算“得分”的平均值,然后为表中的每一行计算“得分”与匹配平均值的差额。 And then sum that PAA value by user. 然后按用户求和该PAA值。

Is it possible to do this via a MySQL query? 是否可以通过MySQL查询来做到这一点? Or do I need PHP? 还是我需要PHP? If it can be done by query, what would that query look like? 如果可以通过查询完成,该查询将是什么样?

plan 计划

  • compute avg scores by match 通过匹配计算平均得分
  • join user scores to avg scores and compute sum of derived difference field by userid 将用户分数与平均分数相结合,并按userid计算得出的差异字段之和

setup 设定

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 )
;

query 询问

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
;

output 产量

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

sqlfiddle sqlfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM