如何计算平均值在范围内的记录

How to count records with averages in range

我需要计算平均成绩从 7.6 到 8.3 的学生人数 我试过了

Select count(*) from tabele
Where AVG(grade)> 7.6
and AVG(Grade)<8.3 
Group by id

但是总是出错

你应该在这里使用 having 子句而不是 where。 sum(count(distinct id)) 也可用于计算值的数量。或者,您可以使用子查询来获得相同的结果。

select sum(count(distinct id)) from table_name
group by id
having AVG(grade) BETWEEN  7.6 and 8.3;

下面的方法是首先按学生 id 汇总并在 HAVING 子句中断言平均成绩要求。然后,子查询以查找此类匹配学生的计数。

SELECT COUNT(*)
FROM
(
    SELECT id
    FROM yourTable
    GROUP BY id
    HAVING AVG(Grade) > 7.6 AND AVG(Grade) < 8.3
) t;

假设您的 RDBMS 支持 window 函数,这是我们可以通过单个查询获取计数的一种方法:

SELECT DISTINCT COUNT(*) OVER () AS total_cnt
FROM yourTable
GROUP BY id
HAVING AVG(Grade) > 7.6 AND AVG(Grade) < 8.3;

像这样的东西应该可以工作

    WITH _CTE AS 
(
    SELECT StudentId, AVG(Grade) as avgGrade
    FROM MyTalbe
    GROUP BY StudentId
)
SELECT COUNT(*)
FROM _CTE
WHERE avgGrade > 7.6
AND avgGrade < 8.3