SELECT CarBrand.BrandName, Count(Cars.ColorName) AS CountOfGreenProducts
FROM (Cars
INNER JOIN CarFacts ON Cars.CarKey = CarFacts.CarKey)
INNER JOIN CarBrand ON CarFacts.BrandKey = CarBrand.BrandKey
GROUP BY CarBrand.BrandName
HAVING Cars.ColorName = "Green";
我正在尝试获取所有绿色汽车的数量,但我收到一条错误,指出“您的查询不包含指定的表达式Cars.ColorName =”Green“作为聚合函数的一部分”我将不胜感激帮助解决此错误的方法。谢谢!
答案 0 :(得分:1)
只是扩展上面的sgeddes评论。
您希望将条件从HAVING
条款移至WHERE
条款。原因是在聚合之前执行WHERE
子句。换句话说,数据库会在Cars
表之前过滤掉INNER JOIN
表中的所有记录以及生成COUNT(Cars.ColorName)
的{{1}}。
HAVING
在聚合后过滤。它几乎是数据库对记录集采取的最后一步。因此,当您说HAVING Cars.ColorName = "Green"
时数据库会混淆,因为Cars.ColorName
不是结果集中的字段。 CountOfGreenProducts
确实存在于结果集中,但您无法对其进行过滤,而#34; Green&#34}因为它是一个数字。因此DB会抛出错误。
所以,相反:
SELECT CarBrand.BrandName, Count(Cars.ColorName) AS CountOfGreenProducts
FROM (Cars
INNER JOIN CarFacts ON Cars.CarKey = CarFacts.CarKey)
INNER JOIN CarBrand ON CarFacts.BrandKey = CarBrand.BrandKey
WHERE Cars.ColorName = "Green"
GROUP BY CarBrand.BrandName;