-1

在 sql server 2005 中不使用 while 循环更新表数据

我问了这个问题,细节是......

在 sql 我有如下表数据

id      type     amount       
1      type1       2000    
2      type1       1000     
3      type2        500    
4      type3       3000    
5      type1       2000   
6      type2        500        
7      type3       5000    
8      type1       1000    

我想在 select 语句中获取数据,如下所示

id      type     amount      current   
1      type1       2000         2000                
2      type1       1000         1000                 
3      type2        500          500                 
4      type3       3000         3000                 
5      type1       2000         3000                  
6      type2       -500            0                 
7      type3       5000         2000
8      type1      -1000         4000 

依此类推,这意味着每种类型都必须具有基于数量类型的当前总量,并且不需要有 while 循环,因为执行需要很长时间

for eg:

in type 1

ID      Amount      current 
1      2000-add       2000                   
2      1000-sub       1000                  
3      2000-add       3000                   
4      1000-add       4000                   

答案是,

SELECT id,
       type,
       amount,
       (SELECT sum(amount)
        FROM   mytable t1
        WHERE  t1.type = t2.type
               AND t1.id <= t2.id) currenttotal
FROM   mytable t2 

现在的问题是假设示例表有 8000 条(它将增加)数据记录,例如

id      type     amount       
1      type1       2000    
2      type1       1000     
3      type2        500    
4      type3       3000    
5      type1       2000   
6      type2        500        
7      type3       5000    
8      type1       1000

以及00:00:02执行我根据上述问题的答案(有2个答案并且都有相同的执行时间)编写的select语句需要时间。如何减少这个执行时间?

4

1 回答 1

2

Try

CREATE UNIQUE INDEX IX ON YourTable(type,id) INCLUDE (amount)

As long as the number of rows per type doesn't get too large the query in your question should be OK.

SQL Server 2012 has better support for calculating running totals than previous versions do. In SQL Server 2012 you could just do

SELECT id,
       type,
       amount,
      SUM(amount) OVER (PARTITION BY type 
                         ORDER BY id ROWS UNBOUNDED PRECEDING) currenttotal
FROM   mytable t2 
于 2013-07-27T08:24:06.893 回答