mysql - 在 WHERE 子句中的 SQL 聚合

标签 mysql sql sql-server

我要做的是:

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/

相关文章:

mysql - 如何仅在包含特定值时显示 SQL 数据

java - Hive 描述分区以显示分区 url

mysql - 来自三个不同表的唯一数据

c# - 在 SQL Server CLR 存储过程中运行进程但 Process.OutputDataReceived 未触发

sql - 使用多个类似条件选择查询

mysql - 获取我的查询的多个结果

MYSQL:如何检查值是否不在特定时间间隔内

mysql - 更新字段值但也应用上限?

mysql - 如何在MySQL中找到计数结果的平均值?

sql-server - tableau 中的计算字段以查找第一行是成功还是失败