Sina zhr Sina zhr - 3 months ago 9
MySQL Question

query for total column in every rows

I couldn't find right query solution to add total column for every row

table

+-----+---------+
|id |amount |
+-----+---------+
|1 |1000 |
+-----+---------+
|2 |2050 |
+-----+---------+
|3 |2666 |
+-----+---------+


needed result

+-----+---------+---------+
|id |amount |total |
+-----+---------+---------+
|1 |1000 |1000 |
+-----+---------+---------+
|2 |2050 |3050 |
+-----+---------+---------+
|3 |2666 |5716 |
+-----+---------+---------+


ps: amount could be +/-

thanks

Answer
SELECT
  *
  ,(@runningtotal:= @runningtotal + t.amount) as RunningTotal
FROM
  TableName t
  CROSS JOIN (SELECT @runningtotal:= 0) var

Yep with a variable you can do it without a sub query. Here is a SQL fiddle of the example. http://sqlfiddle.com/#!9/956a2c/2