【问题标题】:MySQL query to get sum of differences between column and AVG of same columnMySQL查询以获取同一列的列和AVG之间的差异总和
【发布时间】:2015-11-07 09:37:18
【问题描述】:

我有一个包含用户分数的表格,用于游戏:

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

我想汇总每个用户的“高于平均水平的点数”(PAA) - 用户得分高于或低于平均水平的数量。

因此,您需要计算每个“MatchId”的“Score”平均值, 然后为表中的每一行计算 “得分”不同于比赛平均水平。然后将该 PAA 值相加 用户。

是否可以通过 MySQL 查询来做到这一点?还是我需要 PHP?如果可以通过查询来完成,那么该查询会是什么样子?

【问题讨论】:

  • 什么样的游戏涉及浮点值?即使是体操也可以使用小数
  • 你应该先展示你的尝试

标签: php mysql


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2022-01-02
    • 2014-05-11
    • 1970-01-01
    • 2011-11-19
    相关资源
    最近更新 更多