我要做的是:
2. Write a SELECT statement that answers this question:
Which products have a list price that’s greater than the average list price for all products?
Return the ProductName and ListPrice columns for each product.
Sort the results by the ListPrice column in descending sequence.
我想出的SQL代码:
SELECT ProductName, ListPrice
FROM Products
WHERE Products.ListPrice > AVG(ListPrice)
ORDER BY ListPrice DESC
但是这给了我错误:
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
然而,当我手动计算 AVG 并将其作为原始整数插入时:
SELECT ProductName, ListPrice
FROM Products
WHERE Products.ListPrice > 841.895
ORDER BY ListPrice DESC
这行得通。为什么是这样?为什么 AVG(ListPrice) <> 841.895??
修复此错误的最佳方法是什么?
最佳答案
聚合函数 AVG()
将给出一组的平均值。如果您使用没有 GROUP BY
的聚合,则没有定义的组。这就是您的第一个查询失败的原因。您可以使用子查询来绕过该限制:
SELECT ProductName, ListPrice
FROM Products
WHERE ListPrice > ( SELECT AVG(ListPrice) FROM Products )
ORDER BY ListPrice DESC;
关于mysql - 在 WHERE 子句中的 SQL 聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28204470/