使用分组依据更新临时表

时间:2015-10-26 16:07:08

标签: sql sql-server

获取此错误

  

Msg 157,Level 15,State 1,Line 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

1 个答案:

答案 0 :(得分:0)

一般情况下,您可以使用以下事实:您可以在SQL Server中更新common table expressions +应用窗口函数,如下所示:

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

<强> sql fiddle demo

但是在你的问题中,你必须在更新查询中添加#Results表,否则它不清楚SQL Server要更新哪些行