SQL查询聚合不能出现在WHERE子句(AVG)中
嗨,我找不到解决这个问题的方法 聚合不能出现在WHERE子句中,除非它位于HAVING子句或select列表中包含的子查询中,并且被聚合的列是外部引用SQL查询聚合不能出现在WHERE子句(AVG)中,sql,Sql,嗨,我找不到解决这个问题的方法 聚合不能出现在WHERE子句中,除非它位于HAVING子句或select列表中包含的子查询中,并且被聚合的列是外部引用 select p.ProductName, p.UnitPrice from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p where p.UnitPrice > AVG(p.UnitPrice) group by p.UnitPrice 应该是这样的:平均价格是28.3
select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
where p.UnitPrice > AVG(p.UnitPrice)
group by p.UnitPrice
应该是这样的:平均价格是28.3,所以单价高于28.3
ProductName UnitPrice
Uncle Bob's Organic Dried Pears 30,00
Northwoods Cranberry Sauce 40,00
Mishi Kobe Niku 97,00
Ikura 31,00
Queso Manchego La Pastora 38,00
Alice Mutton 39,00
有也不行
select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
group by p.UnitPrice
having p.UnitPrice > AVG(p.UnitPrice)
改用子查询:
select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
where p.UnitPrice > (select avg(p2.UnitPrice)
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p2
);
您需要使用子查询来计算平均值,然后再将其与单价进行比较
select p.ProductName, p.UnitPrice
from northwind.dbo.products p
where p.UnitPrice>
(
select AVG(p2.UnitPrice)
from northwind.dbo.products p2
group by p2.ProductName
having p2.ProductName = p.ProductName
)
您应该确保您的产品名称是唯一的,或者使用产品密钥而不是名称向我们显示一些示例表数据和预期结果-所有内容都是格式化文本,而不是图像。()谢谢你,我花了一个小时的时间来解决这个问题,我试着使用子查询,但没有对“select avg(p2.单价)。。。。。。。但作为select avg(p.单价)``非常感谢