Guest User

Untitled

a guest
Aug 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. Creating a cumulative sum column in MySQL
  2. num
  3. 1
  4. 5
  5. 6
  6. 8
  7. 2
  8. 3
  9.  
  10. num cumulative
  11. 1 1
  12. 2 3
  13. 3 6
  14. 5 11
  15. 6 17
  16. 8 25
  17.  
  18. select a.num, sum(b.num) from ID a, ID b where b.num <= a.num group by a.num order by a.num;
  19.  
  20. Select num as n,
  21. (select sum(num) from ID where num <= n)
  22. from ID order by n;
  23.  
  24. SELECT a.num,
  25. (@s := @s + a.num) AS cumulative
  26. FROM ID a, (SELECT @s := 0) dm
  27. ORDER BY a.num;
  28.  
  29. declare @tmp table(ind int identity(1,1),col1 int)
  30. insert into @tmp
  31. select 2
  32. union
  33. select 4
  34. union
  35. select 7
  36. union
  37.  
  38. select 5
  39. union
  40. select 8
  41. union
  42. select 10
  43.  
  44.  
  45. SELECT t1.col1,sum( t2.col1)
  46. FROM @tmp AS t1 LEFT JOIN @tmp t2 ON t1.ind>=t2.ind
  47. group by t1.ind,t1.col1
  48.  
  49. select t1.col1,(select sum(col1) from @tmp as t2 where t2.ind<=t1.ind)
  50. from @tmp as t1
Add Comment
Please, Sign In to add comment