Skip to content
Advertisement

Rolling sum for a column in mysql

I would like to get the rolling sum for the growth column for the following sample data which can be found here dbfiddle

The output should look like,

My attempt is as follows. I am only getting the total for values in the Growth column

The above gives me the result as,

I want to avoid using procedures,cursors or functions if at all possible. I am using mysql 8.0.17

Advertisement

Answer

You can use SUM() window function but with the correct ordering.
This ordering:

is wrong because DATE_FORMAT() with these parameters returns NULL, so you simply sort by Year.
See the demo.
It is coincidental that you get correct results.

The correct ordering is:

So use this:

See the demo.
Results:

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