我有以下SQL查询,它会计算ID为 1800 的项目的前 100 条目的平均得分。我想概括它来计算每个项目的顶部 100 条目的平均得分,所以如果有10个项目,将要处理的记录数量将是1000,其中每100个对应于一个不同的project_id。任何帮助将不胜感激!
SELECT
score1.project_id, AVG(score1.final_score)
FROM
(SELECT
project_id, final_score
FROM
consultant_project_score
WHERE
project_id = 1800
ORDER BY final_score DESC
LIMIT 100) score1;
答案 0 :(得分:0)
在计算函数中计算平均值的逻辑,并在表格的select查询中调用它。
select project_id,calaverage(project_id) as `average`
from
consultant_project_score
可以按如下方式创建平均函数:
CREATE
FUNCTION `calaverage`(projectid INT)
RETURNS FLOAT
BEGIN
DECLARE average FLOAT;
SELECT
AVG(score1.final_score) INTO average
FROM
(SELECT
project_id, final_score
FROM
consultant_project_score
WHERE
project_id = projectid
ORDER BY final_score DESC
LIMIT 100) score1;
RETURN average;
END