如何逐行获取行的总和

时间:2014-04-18 11:10:07

标签: sql-server

;With T(days,currentvalue)  
AS
(
SELECT a.days,sum(counts) as currentvalue from SUMOP A
group by days
)
Update SUMOP set sumop.currentvalue=T.currentvalue
where sumop.days=T.days 

上面的查询是抛出错误。有语法错误吗?请帮忙

我在执行查询时遇到此错误:

The multi-part identifier "T.days" could not be bound.

3 个答案:

答案 0 :(得分:1)

您可以使用窗口函数计算每天counts的总和:

update  t
set     currentvalue = t.curval
from    (
        select  currentvalue
        ,       sum(counts) over (partition by days) as curval
        from    sumop
        ) t

See it working at SQL Fiddle.

答案 1 :(得分:0)

with之前添加分号,然后使用join更新。

; With T(days,currentvalue)  
AS
(
SELECT a.days,sum(counts) as currentvalue from SUMOP A
group by days
)
Update SUMOP set sumop.currentvalue=T.currentvalue
FROM SUMOP, T where sumop.days=T.days 

答案 2 :(得分:0)

您的CTE T会创建一个行集,因此您需要从联接更新。