gpt4 book ai didi

mysql - 聚合不能出现在 WHERE 子句中,除非它位于 HAVING 子句或选择列表中包含的子查询中

转载 作者:行者123 更新时间:2023-11-29 12:32:46 27 4
gpt4 key购买 nike

嘿,大家好,我正在尝试查找高于其类别中产品的平均 ListPrice 两倍的产品标价。我做了一个类似的问题,就像这样,我使用 HAVING 子句来解决它,但这个不起作用。对我做错了什么有什么建议吗?

SELECT P.Name             NameOfProduct,
PC.Name NameOfProductCategory,
P.ListPrice ProductListPrice,
AVG(P.ListPrice) AverageListPrice
FROM Product P
INNER JOIN ProductCategory PC ON (PC.ProductCategoryID = P.ProductCategoryID)
WHERE (P.ListPrice) > (AVG(P.ListPrice)*2)
GROUP BY P.Name, PC.Name

最佳答案

如您所知,不能在 having 子句中使用聚合函数。您可以使用相关子查询执行您想要的操作:

SELECT P.Name             NameOfProduct,
PC.Name NameOfProductCategory,
P.ListPrice ProductListPrice,
AVG(P.ListPrice) AverageListPrice
FROM Product P INNER JOIN
ProductCategory PC
ON PC.ProductCategoryID = P.ProductCategoryID
WHERE P.ListPrice) > (SELECT AVG(p2.ListPrice)*2
FROM Product p2
WHERE p2.ProductCategoryID = p.ProductCategoryID
)
GROUP BY P.Name, PC.Name, P.ListPrice;

关于mysql - 聚合不能出现在 WHERE 子句中,除非它位于 HAVING 子句或选择列表中包含的子查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27228034/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com