我正在尝试在广告表上创建插入的触发器。尝试编写此光标时
declare Users cursor for
Select "User".IDUser, Sum(Price)
from "User"
inner join Purchase as pu on "User".IDUser = pu.IDUser
inner join PurchaseProduct as pp on pu.IDPurchase = pp.IDPurchase
inner join Product as pr on pp.IDProduct = pr.IDProduct
inner join inserted on pr.IDProduct = inserted.IDProduct
where pr.ProductType = (select ProductType
from Product
inner join Advertisement on Product.IDProduct = Advertisement.IDProduct
inner join inserted on Advertisement.IDProduct = inserted.IDProduct
where Advertisement.IDAdvertisement = inserted.IDAdvertisement)
and Sum(Price) > 50;
我收到此错误
Msg 147,Level 15,State 1,Procedure AutomaticUserAdvertisementScoreCalculating,Line 15 [Batch Start line 113]
聚合可能不会出现在WHERE子句中,除非它位于HAVING子句或选择列表中包含的子查询中,并且要聚合的列是外部引用。
这里可能出现的错误是什么?您可以在下面看到我的数据库结构
提前致谢
答案 0 :(得分:2)
您可以使用HAVING
在聚合后过滤行:
declare Users cursor for
Select "User".IDUser, Sum(Price) from "User"
join Purchase as pu on "User".IDUser = pu.IDUser
join PurchaseProduct as pp on pu.IDPurchase = pp.IDPurchase
join Product as pr on pp.IDProduct = pr.IDProduct
join inserted on pr.IDProduct = inserted.IDProduct
where pr.ProductType = (select ProductType from Product
join Advertisement on Product.IDProduct = Advertisement.IDProduct
join inserted on Advertisement.IDProduct = inserted.IDProduct
where Advertisement.IDAdvertisement = inserted.IDAdvertisement)
GROUP BY "User".IDUser
HAVING Sum(Price) > 50;