通过行更新的方法实现按行累计(可分类目累计)

 1 --======================================  
 2 --通过行更新的方法实现按行累计(可分类目累计)  
 3 --created by 倪斌斌 
 4 --datetime   2020-03-20     
 5 --======================================  
 6 
 7 --SID 累加的排序字段(原表的数据可以是无序的)
 8 --ItemId 累加的类目,如果没有类目字段,就是整表按顺序累计
 9 --SCORE 累加字段
10 declare  @tempTable table(SID   int,ItemId int,  SCORE   int)   
11 insert   @tempTable   
12 select   3,      1000,           10   union   all   
13 select   4,      1000,           20   union   all   
14 select   2,      1000,           30   union   all   
15 select   1,      1001,           40   union   all   
16 select   5,      1001,           50     
17 --查看添加的数据  
18 select * from @tempTable ORDER BY SID 
19 --原表数据不能保证行顺序已经按类目按排序字段存储,
20 --此处通过ROW_NUMBER处理后,行顺序自动被调整成符合可逐行累加的顺序存入待行累计的临时表
21 select *,ROW_NUMBER() OVER(ORDER BY ItemId,SID) as FINDEX into #tempTable from @tempTable  
22 --======================================  
23 
24 --声明变量   
25 declare   @score   int,@itemId   int   
26 set   @score    =   0   
27 SET      @itemId    =    0
28 --开始更新,注意SQL执行更新时,是按行按存储的顺序更新数据的.  
29 update   #tempTable     
30 set   @score   =   case   when   @itemId   =   ItemId   then     @score   +   SCORE   else   SCORE   end,   
31       @itemId  =   ItemId,
32       SCORE    =   @score   
33 --查看更新后的结果  
34 select   *   from   #tempTable 
35  
36 --最终可以再按照唯一性字段与原表数据关联反写累计字段的值,比如此处可通过字段SID关联
37 update t1 set t1.SCORE=t2.SCORE from @tempTable t1
38 inner join #tempTable t2 on t1.SID=t2.SID
39 
40 select * from @tempTable ORDER BY SID
41 
42 drop table #tempTable
43 --======================================  
原文地址:https://www.cnblogs.com/nikyxxx/p/12529703.html