SQL:需要从一个表中获取MAX值并除以另一个表中的总行数

时间:2014-02-05 23:19:18

标签: sql

我有一个基于用户的基础上的一堆课程分数

------------------------
|uid |lesson_id |score |
------------------------
|1   |0         |20    |
|1   |0         |25    |
|1   |0         |15    |
|1   |0         |40    |
|1   |1         |70    |
|1   |0         |10    |
|1   |1         |20    |
|1   |1         |55    |
|1   |1         |55    |
|1   |0         |5     |
|1   |2         |65    |
------------------------

我还有一张可以得分的所有课程表:

------------
|lesson_id |
------------
|0         |
|1         |
|2         |
|3         |
|4         |
|5         |
------------

我需要根据第一张表中的分数计算第二张表中每节课的最高分数,并取第二张表中课程数的平均值:

因此,分数表的最高分数是(对于用户1):

-----------------------
|lesson_id |max_score |
-----------------------
|0         |40        |
|1         |70        |
|2         |65        |
-----------------------

我需要总结一下:175并除以表2中的课程总数:6应给出答案29.16

任何想法如何在一个声明中做到这一点?

我可以得到得分表(对于用户1)的所有最大值的平均值,如下所示:

SELECT AVG(max_score) AS avg_max_score FROM 
(
    SELECT uid, lesson_id, MAX(score) AS max_score FROM cdu_user_progress 
    AND uid =1
    GROUP BY lesson_id 
) AS m

1 个答案:

答案 0 :(得分:0)

SELECT
    AVG(max_score)
FROM
   (

    SELECT
         lesson.lesson_id,
         max(isNull(score,0)) as max_score
    FROM
         lesson
    LEFT JOIN
         cdu_user_progress
    ON
         lesson.lesson_id = cdu_user_progress.lesson_id
    GROUP BY
         lesson.lesson_id
   ) AS m