Skip to content
Advertisement

Select date and value between two dates with cumulative sum

I’m trying to sum every day between two dates without lose the last value.

A little bit of context:

So I made this query:

The first result is ok, but the sum is wrong. I got:

But I expect:

Advertisement

Answer

If you are running MySQL 8.0, just use window functions, as demonstrated by Tim Biegeleisen.

In earlier versions, user variables are more efficient than a correlated subquery on a large dataset. However they are a bit tricky to use. For one, you don’t need a subquery. And a little trick is needed to properly manage the ordering of the sum. I would phrase your query as:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement