SQL - 总体平均分数

时间:2014-08-21 18:01:07

标签: sql sum distinct average

我有一张这样的表:

[challenge_log]
User_id   |    challenge  |  Try   |   Points
==============================================
  1               1           1            5
  1               1           2            8
  1               1           3            10
  1               2           1            5
  1               2           2            8
  2               1           1            5
  2               2           1            8
  2               2           2            10

我想要整体平均分。为此,我相信我需要3个步骤:

步骤1 - 获取每个挑战中每个用户的MAX值(点数):

User_id   |    challenge  |  Points
===================================
  1               1           10
  1               2           8
  2               1           5
  2               2           10

步骤2 - SUM一个用户的所有MAX值

User_id   |  Points
===================
  1           18
  2           15

第3步 - 平均值

AVG = SUM (Points from step 2) / number of users = 16.5

你能帮我找一个查询吗?

4 个答案:

答案 0 :(得分:2)

您可以通过将总点数除以不同用户数来获得总体平均值。但是,您需要每次挑战的最大值,因此总和有点复杂。一种方法是使用子查询:

select sum(Points) / count(distinct userid)
from (select userid, challenge, max(Points) as Points
      from challenge_log
      group by userid, challenge
     ) cl;

您也可以通过查找where子句中的最大值来进行一级聚合:

select sum(Points) / count(distinct userid)
from challenge_log cl
where not exists (select 1
                  from challenge_log cl2
                  where cl2.userid = cl.userid and
                        cl2.challenge = cl.challenge and
                        cl2.points > cl.points
                 );

答案 1 :(得分:1)

尝试使用这些尺寸。

  • 总体平均值

    select avg( Points ) as mean_score
    from challenge_log 
    
  • 每次挑战均值

    select challenge ,
           avg( Points ) as mean_score
    from challenge_log
    group by challenge
    

如果您想计算每个用户每次挑战最高得分的平均值,那么您并没有完全提高复杂程度:

  • 总体平均值

    select avg( high_score )
    from ( select user_id   ,
                  challenge ,
                  max( Points ) as high_score
           from challenge_log
         ) t
    
  • 每次挑战均值

    select challenge ,
           avg( high_score )
    from ( select user_id   ,
                  challenge ,
                  max( Points ) as high_score
           from challenge_log
         ) t
    group by challenge
    

答案 2 :(得分:0)

在第1步之后

SELECT USER_ID, AVG(POINTS)
FROM STEP1
GROUP BY USER_ID

答案 3 :(得分:0)

您可以将步骤1和2组合到单个查询/子查询中,如下所示:

    Select BestShot.[User_ID], AVG(cast (BestShot.MostPoints as money))
    from (select tLog.Challenge, tLog.[User_ID], MostPoints = max(tLog.points) 
            from dbo.tmp_Challenge_Log tLog
            Group by tLog.User_ID, tLog.Challenge
        ) BestShot
    Group by BestShot.User_ID

子查询确定每个用户/质询组合的最多点,外部查询获取这些最大值并使用AVG函数返回它们的平均值。最后一个Group By告诉SQL平均每个User_ID的所有值。