2

I am trying to run a query that gets the cumulative sum of a column in one of my tables. It looks like this:

set @csum := 0;
select order_date, Amount, (@csum := @csum + Amount) as cumulative_sum
from Orders
order by order_date

However, when running this, I get all NULLs for the cumulative_sum. Anything I"m doing wrong? Thanks!

3
  • Why not just do sum(Amount) as cumulative_sum.... Commented Jun 9, 2015 at 22:38
  • It occurs to me that if you don't explicitly declare @csum, it's probably going to be initialised as an INT, and 'Amount' is probably - what, decimal? Try set @csum := 0.0; Commented Jun 9, 2015 at 22:51
  • Mike K, 100% correct. How would I declare it as an INT (if I didn't want decimals) Commented Jun 10, 2015 at 0:19

3 Answers 3

1

I would suggest just doing:

select order_date, Amount, sum(Amount) as cumulative_sum
from Orders
order by order_date

If you need to store the value in a variable then you could do:

SELECT @Variable = sum(Amount)
from Orders

And maybe add a GroupBy if you wanted to sum the amounts per day

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry if I wasn't clear. The above query you gave will only give one row that sums all the Amounts. What I want is a cumulative sum over time, so if the Amounts were, 1, 5, 7, 10, the cumulative column should be 1, 6, 13, 23.
1

I would guess that Amount could sometimes be NULL. Try this version:

select o.order_date, o.Amount,
       (@csum := @csum + coalesce(o.Amount, 0)) as cumulative_sum
from Orders o cross join
     (select @csum := 0) params
order by o.order_date;

Comments

1

Since MySQL 8, a much better approach than using MySQL's vendor specific variables (and relying on the non-declarative nature of their calculation) is to use SQL standard window functions. Your query can be rewritten as such:

SELECT
  order_date,
  amount,
  sum(amount) OVER (ORDER BY order_date)
FROM orders
ORDER BY order_date

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.