Skip to content
Advertisement

MySQL Running Total By Group, Time Interval

I would like to take a table of customer orders like this:

And create a table calculating a cumulative running total by week, segmenting the weeks by 7 days starting at the earliest date (2020-03-01, 2020-03-08, etc.). Something like:

Thanks for the help!

Advertisement

Answer

You can use aggregation and window functions (this requires MySQL 8.0). It is easier and more scalable to put the weeks in rows than in columns:

You can pivot this to columns as well – but you need to enumerate the weeks:

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