请参阅中的以下查询: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
之外还包含任何其他条件,则不能执行此方法。