如何获得SQL查询的前N行的平均值?

时间:2016-08-26 02:14:56

标签: sql

我正在尝试

SELECT AVG(q."level")
FROM "Questions" q, "QuestionScores" qs
WHERE qs."QuestionId" = q."id"
AND qs."StudentId"=13
AND q."TopicId" = 45
AND qs."version" = 8
ORDER BY qs."score" DESC
LIMIT 3 

但是它说我需要在GROUP BY中使用qs."score"或者在聚合函数中使用它。我想要的是平均排名前三的问题级别(按分数排名)。

1 个答案:

答案 0 :(得分:3)

您需要使用子查询获取前n行 然后获得平均值:

SELECT AVG(level) FROM (
    SELECT q.level
    FROM Questions q, QuestionScores qs
    WHERE qs.QuestionId = q.id
    AND qs.StudentId=13
    AND q.TopicId = 45
    AND qs.version = 8
    ORDER BY qs.score DESC
    LIMIT 3
) x

我建议您使用现代(超过25年)join语法:

   SELECT AVG(level) FROM (
    SELECT q.level
    FROM Questions q
    JOIN QuestionScores qs ON qs.QuestionId = q.id
    WHERE qs.StudentId=13
    AND q.TopicId = 45
    AND qs.version = 8
    ORDER BY qs.score DESC
    LIMIT 3
) x