[英]Update Temp Table with Group By
Getting this error 得到这个错误
Msg 157, Level 15, State 1, Line 20
消息157,第15层,状态1,第20行
An aggregate may not appear in the set list of an UPDATE statement.聚合可能不会出现在UPDATE语句的设置列表中。
My UPDATE
statement: 我的
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
in general, you can use the fact that you can update common table expressions
in SQL server + apply the window function, like this: 通常,您可以使用以下事实:可以在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
But in your question, you have to add #Results
table to your update query otherwise it's not clear for SQL Server which rows to update 但是在您的问题中,必须将
#Results
表添加到更新查询中,否则SQL Server不清楚要更新哪些行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.