簡體   English   中英

使用分組依據更新臨時表

[英]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

sql小提琴演示

但是在您的問題中,必須將#Results表添加到更新查詢中,否則SQL Server不清楚要更新哪些行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM