选择大于指定值的列

时间:2014-02-19 22:48:54

标签: sql group-by distinct average

这是我目前的代码:

select distinct categoryid, min(weight), max(weight), round(avg(weight), 2) as AVG_WEIGHT
from inventorypart
where categoryid is not null
group by categoryid;

我需要选择平均重量大于4的类别。

我尝试了以下但没有成功

where categoryid is not null and avg(weight) > 4

1 个答案:

答案 0 :(得分:0)

WHERE关键字不能与聚合函数一起使用,因为在GROUP BY之前应用了WHERE。改为使用HAVING:

SELECT DISTINCT categoryid, MIN(weight), MAX(weight), ROUND(AVG(weight), 2) AS AVG_WEIGHT
FROM inventorypart
WHERE categoryid IS NOT NULL
GROUP BY categoryid
HAVING AVG(weight) > 4