WHERE子句中的SQL聚合

时间:2015-01-28 23:35:09

标签: 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并将其作为原始int插入时:

SELECT ProductName, ListPrice
FROM Products
WHERE Products.ListPrice > 841.895 
ORDER BY ListPrice DESC

这很有效。为什么是这样?为什么AVG(ListPrice)<> 841.895 ??

解决此错误的最佳方法是什么?

3 个答案:

答案 0 :(得分:2)

汇总函数AVG()将给出组的平均值。如果使用不带GROUP BY的聚合,则没有已定义的组。这就是您的第一个查询失败的原因。您可以使用子查询来解决该限制:

SELECT ProductName, ListPrice
  FROM Products
 WHERE ListPrice > ( SELECT AVG(ListPrice) FROM Products )
 ORDER BY ListPrice DESC;

答案 1 :(得分:1)

您正在引用在查询本身中未返回的计算字段。

WHERE子句只能引用某处存在的数据,但幸运的是,它可以存在于子查询中,嵌套在WHERE子句中。

另一种选择是尝试将其放在HAVING子句中,而不是WHERE中。但是,在这种情况下,最好将AVG置于子查询中,例如。

SELECT ProductName, ListPrice
FROM Products
WHERE Products.ListPrice > (SELECT AVG(ListPrice) FROM Products)

此语句将创建一个临时子表,由您的" WHERE"子句。

答案 2 :(得分:-1)

以上问题都是有趣的方法。最好的方法是使用where子句之后的“HAVING”子句。

你会这样写:

SELECT ProductName, ListPrice
FROM Products
group by productName,ListPrice
having Products.ListPrice > AVG(ListPrice) ;

您可以将HAVING视为处理聚合列的WHERE子句。