douju7765 2015-11-07 09:37
浏览 99
已采纳

MySQL查询获取列与同一列的AVERAGE之间的差异总和

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.

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. And then sum that PAA value by user.

Is it possible to do this via a MySQL query? Or do I need PHP? If it can be done by query, what would that query look like?

  • 写回答

1条回答 默认 最新

  • dtzd65908 2015-11-07 09:55
    关注

    plan

    • compute avg scores by match
    • join user scores to avg scores and compute sum of derived difference field by 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号