Не сработает, если сгруппировать по цене, поэтому каждая цена будет уникальной, и ни одна из них не будет на самом деле больше средней.
create table dbo.Item
(
Name varchar(50) not null,
Price decimal(18,0) not null -- Change it to Price decimal(12,2) if really want it to work
)
GO
insert into dbo.Item (Name, Price)
values
('Triangle', 2.5),
('Triangle', 3.5),
('Square', 3.5),
('Square', 4.5)
GO
select it.Name, AVG(it.Price) as [AveragePrice]
from dbo.Item it
group by it.Name
having it.Price > avg(it.price)
/*
Msg 8121, Level 16, State 1, Line 20
Column 'dbo.Item.Price' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.
*/
GO
select it.Name, it.Price, AVG(it.Price) as [AveragePrice]
from dbo.Item it
group by it.Name, it.Price
having it.Price > avg(it.price)
/* No rows */
GO
Если вы просто запустите соответствующую часть, это станет ясно.
select it.Name, it.Price, AVG(it.Price) as [AveragePrice]
from dbo.Item it
group by it.Name, it.Price
Name Price AveragePrice
-------------------------------------------------- --------------------------------------- ---------------------------------------
Triangle 3 3.000000
Square 4 4.000000
Triangle 4 4.000000
Square 5 5.000000
(4 row(s) affected)
Полагаю, вы хотите что-то более похожее на это:
/* Remeber to change table column to Price decimal(12,2) not null */
/* or the lack of decimal points will make it no to work */
select * from dbo.Item it2
join
(
select it.Name, AVG(it.Price) as [AveragePrice]
from dbo.Item it
group by it.Name
) as FOO
on FOO.Name = it2.Name
where FOO.[AveragePrice] < it2.Price
GO