我正在尝试使用以下查询更新我的临时表的列:
Update T
Set T.ConsumedQuantity = SUM(MA.Quantity)
from @TempTable T
Join DefaultShopView DSV on DSV.OperationId =@OpId
join MySpec MS with(nolock) on MS.WorkRequest = DSV.WorkRequest
join MyActual MA with(nolock) on MA.SpecId = MS.SpecId
但得到错误:
聚合可能不会出现在UPDATE语句的集合列表中。
如何更新值?
答案 0 :(得分:0)
您可以使用:
Update T
Set T.ConsumedQuantity = (select SUM(MA.Quantity) from @TempTable
Join DefaultShopView DSV on DSV.OperationId =@OpId
join MySpec MS with(nolock) on MS.WorkRequest = DSV.WorkRequest
join MyActual MA with(nolock) on MA.SpecId = MS.SpecId )
from @TempTable T
Join DefaultShopView DSV on DSV.OperationId =@OpId
join MySpec MS with(nolock) on MS.WorkRequest = DSV.WorkRequest
join MyActual MA with(nolock) on MA.SpecId = MS.SpecId
答案 1 :(得分:0)
最简单的使用CTE:
;WITH CTE as (
SELECT T.IDENTIFIERS_FIELDS, SUM(MA.Quantity) as MA_Sum
from @TempTable T
DefaultShopView DSV on DSV.OperationId =@OpId
join MySpec MS with(nolock) on MS.WorkRequest = DSV.WorkRequest
join MyActual MA with(nolock) on MA.SpecId = MS.SpecId
GROUP BY GROUPING_FIELDS_IF_ANY
)
Update T
Set T.ConsumedQuantity = MA_Sum
from @TempTable T
Join CTE on T.IDENTIFIERS_FIELDS = CTE.IDENTIFIERS_FIELDS
如果您需要分组,阅读问题不明确。将此选择作为模板来自定义最终查询。