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

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

报告相同问题?

悬赏问题

  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM