编码笔记

导航

SQL逐行累加实现

因业务需要查询实现第二行的数据为第一行加上第二行的值来处理,写下SQL语句,特记录如下,以备后用!

 

  1. select a.id, sum(b.a) as b  
  2.       from   tt as a, tt as b  
  3.       where  a.id>=b.id  
  4.       group by a.id  

 

说明tt为表名,id为排序名,a为数值

 

 IDENTITY(INT,1,1)为自增
网上找的资料如下:
 
  1. --对表中数据逐行累加  
  2.   
  3. declare  @tempTable table(SID   int,  SCORE   int)   
  4. insert   @tempTable   
  5. select   1,                 10   union   all   
  6. select   2,                 20   union   all   
  7. select   3,                 30   union   all   
  8. select   4,                 40   union   all   
  9. select   5,                 50     
  10. --查看添加的数据  
  11. select * from @tempTable  
  12. drop table temptable  
  13. select * into tempTable from @tempTable  
  14. --=====================================================  
  15. --1.使用子查询来计算累加和(非常好的一个方法)  
  16. --=====================================================  
  17.   
  18. SELECT   
  19. TB1.SID,   
  20. SUM(TB2.SCORE) SCORE   
  21. FROM   
  22. tempTable TB1, (SELECT SID, SCORE   
  23.                 FROM TempTable   
  24.                 )TB2   
  25. WHERE   
  26. TB1.SID >= TB2.SID   
  27. GROUP BY TB1.SID   
  28.   
  29. --======================================  
  30. SELECT SID,  
  31. SUM(SCORE) AS SCORE,  
  32.          (   
  33.             SELECT SUM(SCORE)  
  34.             FROM TempTable  
  35.             WHERE (SID <= A.SID)  
  36.         )  
  37.         AS [SUM_SCORE]  
  38. FROM TempTable AS A  
  39. GROUP BY SID  
  40. ORDER BY SID  
  41.   
  42.   
  43. --======================================  
  44. --2.通过更新的方法实现  
  45. --======================================  
  46. --声明变量   
  47. declare   @num   int,@SID   int   
  48. set   @num   =   0   
  49. --开始更新,注意SQL执行更新时,是一行行更新数据.  
  50. update   @tempTable     
  51. set   @num   =   case   when   @SID   <=   SID   then     @num   +   SCORE   else   SCORE   end,   
  52.       @SID   =   SID,   
  53.       SCORE   =   @num   
  54. --查看更新后的结果  
  55. select   *   from   @tempTable   
  56.   
  57. --===========注意应用此方法时,SID是有序存储的===================  
  58.   
  59.   
  60. --======================================  
  61. --3.通过查询的方法实现  
  62. --======================================  
  63. select   
  64. sum (case  when sid<=1 then score endas S1,  
  65. sum (case  when sid<=2 then score endas S2,  
  66. sum (case  when sid<=3 then score endas S3,  
  67. sum (case  when sid<=4 then score endas S4,  
  68. sum (case  when sid<=5 then score endas S5  
  69. from tempTable  
  70.   
  71. --===========注意应用此方法时,SID数量是已知,但可以是无序存储的=============  

posted on 2013-02-27 19:25  封三郎  阅读(8332)  评论(0编辑  收藏  举报