0

I want to get the current sum based on previous data. Exemple:

*******************************************
*    Current balance    *    Total sum    *
*******************************************
     8500                    8500
     -500.50                 7999.50
     380.90                  8380.40
     -5500                   2880.40

I don't have any own code to show because I don't know how to accomplish this, besides using a simple SUM() (SELECT SUM(data_sum) FROM table ...).

I have found many similar questions of this but I don't understand the answers (example 1).

Here's my table:

`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(11) DEFAULT NULL,
`id_account` int(11) DEFAULT NULL,
`id_account_to` int(11) DEFAULT NULL,
`id_store` int(11) DEFAULT NULL,
`id_image` int(11) DEFAULT NULL,
`data_name` varchar(45) NOT NULL,
`data_name_short` varchar(45) NOT NULL,
`data_sum` decimal(10,2) DEFAULT NULL,
`data_file` text NOT NULL,
`data_note` text NOT NULL,
`is_transfered` tinyint(4) DEFAULT NULL,
`add_time` tinyint(4) DEFAULT NULL,
`datetime_payed` datetime NOT NULL,
`datetime_added` datetime NOT NULL,
`datetime_edited` datetime NOT NULL

Now to my question: how can I make the SQL query calculate the running total like in the first example, based on the table above?

Community
  • 1
  • 1
Airikr
  • 6,258
  • 15
  • 59
  • 110
  • Possible duplicate of [Calculate a running total in MySQL](http://stackoverflow.com/questions/664700/calculate-a-running-total-in-mysql) – sgeddes Oct 28 '15 at 01:21
  • @sgeddes And that's the thing (and as I clearly said in my question): I don't understand the answer! – Airikr Oct 28 '15 at 01:22
  • You referenced a solution to `sql server` but you tagged `mysql` -- much different implementation... Another great post -- http://stackoverflow.com/a/2563940/1073631 – sgeddes Oct 28 '15 at 01:29
  • The question was almost the same as mine and I found that question after a Google search. As I said in my question, I didn't know how the SQL query would look like since I have never done this before. Gordon did answer my question correctly though. – Airikr Oct 28 '15 at 01:33

1 Answers1

0

You can do this using variables:

select data_sum, (@s := @s + data_sum) as cume_sum
from table t cross join
     (select @s := 0) params
order by ??;

When doing a cumulative sum, you should be ordering by some value (normally a time column).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786