Skip to content
Advertisement

Rolling Sum for Last 12 Months in SQL

I’m trying to get the rolling sum for the past 12 months (Oct 2019-Sept 2020, etc.)> So far, I figured out to get the current year total (which I also want), however, I’m stuck on a legit 12 month rolling sum.

here’s what my current output looks like

AS you can see, it resets at the beginning of the year for the last column. Any ideas?

Advertisement

Answer

Basically, you want to remove the partition by clause from the rolling 12 month sum. I would also suggest a few optimizations to the query:

The main change is that the payout_month is computed only once, in a lateral join, using datefromparts(). You can then use it all over the query, and consistently in the order by clauses of the window functions.

Note that your strategy will fail to produce a proper results if you ever have a month without any sale (the rows clause of the window function will spread over the preceding month, which is not what you want). If that’s something that may happen, then an alternative is a subquery, or another lateral join.

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