SQL比较hasing cluster中的两个聚集函数



请参阅中的以下查询:http://www.zentut.com/sql-tutorial/understanding-correlated-subquery/

SELECT t1.categoryID, categoryName
From products t1 INNER JOIN  categories c ON c.categoryID = t1.categoryID
GROUP BY categoryID
HAVING MAX(unitprice) > ALL(
                             SELECT  2 * AVG(unitprice)
                             From products t2
                             WHERE t1.categoryID = t2.categoryID) 

我们可以使用HAVING MAX(单价)>2*AVG(单价)吗?问题是我们能比较一下吗同一子句中的两个聚合函数?我看到它们总是嵌套第二个集合,为什么?

当然可以有HAVING MAX(unitprice) > 2 * AVG(unitprice)。您可以从categoryId组中检索MAX。事实上,您有一个子查询,它使用的categoryId与您在分组中使用的完全相同,您可以毫无疑问地使用AVG(unitprice)

SELECT t1.categoryID, categoryName
From products t1 INNER JOIN  categories c ON c.categoryID = t1.categoryID
GROUP BY categoryID
HAVING MAX(unitprice) > 2 * AVG(unitprice)

如果子查询中的WHERE子句除了categoryId之外还包含任何其他条件,则不能执行此方法。

最新更新