Sql进步总和

Cor*_*rei 5 sql t-sql sql-server sql-server-2008

我有下表:

CREATE TABLE tbl_proc(
    [proc] float,
    subscriber bigint   
)
Run Code Online (Sandbox Code Playgroud)

数据:

proc | subscriber
-----|-----------
0.7  | 123456   
0.5  | 1234567  
0.3  | 12345    
0.3  | 45678    
0.3  | 1234 
0.2  | 123455   
0.1  | 894562   
Run Code Online (Sandbox Code Playgroud)

我想找到一个很好的方法来向表中添加一个新列,表示上述值的总和.

结果:

proc | subscriber | col3
-----|------------|------------
0.7  | 123456     | 0.7
0.5  | 1234567    | 1.2 -- 0.7 + proc
0.3  | 12345      | 1.5
...
Run Code Online (Sandbox Code Playgroud)

我找到了以下方法:

Select a.[proc],SUM(b.[proc])
from tbl_proc a, tbl_proc b
where a.[proc] <= b.[proc] and (a.[proc] <> b.[proc] or a.subscriber >= b.subscriber)
group by a.[proc],a.subscriber
order by a.[proc] desc
Run Code Online (Sandbox Code Playgroud)

在我的表中,数据按proc排序.订阅者列也是唯一的.

我发现这种方法有点贵(我的桌子很大).由于性能原因,我没有考虑过光标 - 就像解决方案一样.

有什么建议?


更新:

我再搜索了一下这个问题,并在此页面上找到了"更新到本地变量"解决方案:

http://geekswithblogs.net/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx

据我测试,这证明是迄今为止最好的解决方案.

声明@runningTotal float = 0

UPDATE tbl_proc SET @RunningTotal = new_col = @RunningTotal + [proc] FROM tbl_proc

Mar*_*ith 9

这通常称为计算运行总计.

有一种非常快速的方法可以做你想要做的事情,称为" 古怪的更新 ",但它依赖于无证件的行为.

除了游标之外,游标是大型集合的最快方式,因为这些游标的工作负载呈线性增长,而三角形连接工作负载呈指数级增长(直到下一个版本和改进的OVER子句).

有关问题的更多信息,请参阅Itzik Ben Gan的此文档.