I have a foreach that prints all of my data from the database. The data looks like this:
data_sum
63
78
25
35
For each row in the loop I want to add the sum, like this:
data_sum
63
141
166
201
I have tried to use this SQL query:
SET @csum := 63;
SELECT id_account, data_sum, is_expense, (@csum := @csum + data_sum) AS cumulative_sum FROM economy_events
WHERE id_account = '4'
AND is_expense = '1'
But I’m only getting SQLSTATE[HY000]: General error when I try it out. This is the first time I’m trying to use this method. What have I done wrong?
Thanks in advance.
Your query works in MySQL (at least 5.1, 5.5, and 5.6) when pasted directly from your question.
See this SQLfiddle: http://sqlfiddle.com/#!8/53241/1/1
Your should however initialize @csum to 0 in order to reproduce your desired output.
Also, in order for the cumulative sums to be meaningful, you will need to add an
order byclause to your query.If you are running the query from some programming language, the problem might be trouble with continuation lines, or that the query consists of two statements.
You may try rewriting the query as