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數量是已知,但可以是無序存儲的=============  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM