[英]Update Temp Table with Group By
得到这个错误
消息157,第15层,状态1,第20行
聚合可能不会出现在UPDATE语句的设置列表中。
我的UPDATE
语句:
UPDATE #Results
SET CustomerName = dbo.GetCustomerNameByCustomerId(CustomerId),
TotalIncremental = Sum(IncrementalDollarsDebitCredit),
TotalDeficiency = 0
FROM
IncrementalCreditHeader ICH
INNER JOIN
IncrementalCreditHistory IC ON IC.IncrementalCreditID = ICH.IncrementalCreditID
WHERE
IC.BillingPeriodStartDate < = '2015-07-01 00:00:00.000'
AND ICH.ARCreatedFlag = 'Y' AND ICH.ActiveFlag = 1
通常,您可以使用以下事实:可以在SQL Server中更新common table expressions
,并应用window函数,如下所示:
create table temp (client_id int, amount int, total_amount int)
insert into temp (client_id, amount)
select 1, 10 union all
select 1, 15 union all
select 2, 5 union all
select 2, 7 union all
select 2, 15
;with cte as (
select total_amount, sum(amount) over(partition by client_id) as new_total_amount
from temp
)
update cte set
total_amount = new_total_amount
--------------------------------
client_id amount total_amount
1 10 25
1 15 25
2 5 27
2 7 27
2 15 27
但是在您的问题中,必须将#Results
表添加到更新查询中,否则SQL Server不清楚要更新哪些行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.