Reputation: 175
Hi I can't find a solution how to fix this problem.
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.
select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
where p.UnitPrice > AVG(p.UnitPrice)
group by p.UnitPrice
Should be like this : AVG is 28.3 so UnitPrice higher than 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
Having also don't work
select p.ProductName, p.UnitPrice
from [DESKTOP-509LB9L\MSSQLSERVER01].northwind.dbo.products p
group by p.UnitPrice
having p.UnitPrice > AVG(p.UnitPrice)
Upvotes: 2
Views: 270
Reputation: 5452
You need to use a subquery to compute average before compare it to unit price
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
)
You should ensure your product name is unique or use the product key instead of name
Upvotes: 1
Reputation: 1269563
Use a subquery instead:
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
);
Upvotes: 1