Unlock a world of possibilities! Login now and discover the exclusive benefits awaiting you.
Nov 30, 2022 9:45:07 AM
May 4, 2013 3:53:31 PM
A question that gets asked regularly is how to calculate a rolling measure over a period of N-months (or weeks or days). For example a 12-month rolling total or a 4-week rolling average. There are several ways to do this. But these approaches have some limitations that need to be kept in mind. I'll try to explain these approaches and some of their limitations.
First let's load some sample data. The SalesData table below will contain sales amount values for twelve consecutive months.
SalesData:
load * inline [
Month, Amount
1,6
2,4
3,7
4,3
5,4
6,9
7,5
8,7
9,8
10,6
11,9
12,7
];
This is a very simple table with little data, but this enough for demonstration purposes.
Once this data is loaded it's possible to create a straight table chart object to display the amount per month and a running total. As expected Month is used as dimension. The expression sum(Amount) will display the amount per month. Now let's add an expression to calculate a running total over three month periods.
This can be done in two ways. The first uses the Accumulation option for expressions. The same expression sum(Amount) is used, but now the Accumulation option is set to 3 Steps Back:
The second option uses the rangesum function. That expression looks like this:
rangesum(above(sum(Amount),0,3))
This sums the Amount value on current row and on the previous two rows. The resulting straight table looks like this:
This looks good. The rolling 3 months amount is calculated correctly. But what happens if a selection of months is made?
The rolling 3 month amount for month 4 is now 3 instead of 14. This is because month 1,2 and 3 are no longer included in the calculation for the rolling 3 month total.
The accumulation option has another issue. It only works when only one dimension is used in the straight table. The rangesum expression can be modified so it can calculate across dimension borders, but the accumulation option can't. The modified rangesum expression adds the total keyword to the above() function:
rangesum(above(total sum(Amount),0,3))
This goes some way to doing what we want, but the issue of displaying the wrong rolling 3 month amount for month 4 isn't solved yet. Contrary to what I first thought there is a solution for this, as Henric pointed out to me in the comments below. By combining the rangesum with the aggr function it's possible to calculate the correct rolling 3 month amounts for each month. The expression needed for that looks like this:
sum(aggr(rangesum(above(total sum({<Month=>}Amount),0,3)),Month))
Read Elif's blog post Accumulative Sums for a more complete explanation.
How about set analysis expressions?
This expression should calculate the sum of amount for the three month period:
sum({<Month={'>=$(=only(Month)-2)<=$(=only(Month))'}>}Amount)
But notice the only() function. This requires that only one month value is selected. After selecting month 4 the result looks like this:
This shows the selected month, but also the two previous months. And the values are not accumulated.
Ok, but what about the max function instead of only?
sum({<Month={'>=$(=max(Month)-2)<=$(=max(Month))'}>}Amount)
That gives a different result, but still not what we're looking for:
Now only the last three months are shown and again the values are not accumulated.
The 'problem' is that the set is calculated once for the entire chart, not per row. This means that it's not possible here to use Month both as a dimension and in the set modifier in the expression.
There's still an option left to discuss: AsOf tables.
The AsOf table links a period with all the periods in the rolling period. In this example months are used, but it can be applied to any type of period like hours, days or weeks.
For the three month periods needed for a rolling 3 month total this means a month should be linked to itself, the previous month and the month before the previous month. The only exceptions are the first month, which is itself the rolling 3 month period, and the second month that together with the first month is its rolling 3 month period. There are no months before the first month so the first two months cannot run over 3 months.
The AsOf table needed for the rolling 3 month calculations looks like this:
This table can be created like this:
AsOfMonth:
load
Month as Month_AsOf,
Month + 1 - IterNo() as Month
Resident SalesData
while IterNo() <= 3;
right join load Month Resident SalesData;
What this does is create three records for every month using the while statement. But that also creates three records for month 1 and 2. This would create a month 0 and a month -1. The right join is used to remove those incorrect month values.
Now that the AsOfMonth table is created the Month_AsOf field can be used instead of the Month field in the straight table. The expression for the straigh table is simply sum(Amount).
The straight table now shows the correct rolling 3 month total for month 4.
This can be expanded a little so not only the rolling 3 month can be shown, but also the amount for the month itself. To achieve this the AsOf table is modified by adding a field to label the type of period. And records are added to the table so each Month_AsOf value is linked to the matching Month value:
AsOfMonth:
load 'Current' as Type,
Month as Month_AsOf,
Month as Month
Resident SalesData;
Concatenate (AsOfMonth)
load 'Rolling 3' as Type,
Month as Month_AsOf,
Month + 1 - IterNo() as Month
Resident SalesData
while IterNo() <= 3;
right join load Month Resident SalesData;
There are now two types of periods available: Current and Rolling 3. Additional period types can be added for example for Rolling 6, Rolling 12 month and Year-to-Date periods. You can find examples of these types in the attached AsOf Table Examples.qvw document.
The period type can be used in the chart expressions to calculate the amount for the wanted period:
Current amount: sum({<Type={'Current'}>}Amount)
Rolling 3 month amount: sum({<Type={'Rolling 3'}>}Amount)
Concluding, there are two solutions that do what we want:
1. The rangesum-aggr combination
2. The AsOf table
The first has the advantage that no changes to the data model are needed. It's also possible to dynamically change the period to aggregate over by using a variable instead of a hardcoded number of periods. A disadvantage is that that it's a somewhat complicated expression that also comes with a performance cost.
The AsOf needs changes in the data model to create the AsOf table and fill it with the necessary records. The advantage is that it likely performs better on large data sets. It's also quite versatile since you can add several sets of records to meet different scenario's. The expressions you end up with in the charts are also less complicated. That said, it will likely take you some time to fully understand the AsOf table concept and realize all the places where you can put it to good use.
In the end you'll have to decide for yourself which solution is appropriate in your situation. With regards to the performance of one or the other solution, you will simply have to test to discover if the performance is acceptable. But of course such testing is already part of your development process, right?
I'd like to thank John Witherspoon for introducing me to the AsOf tables concept and Henric for pointing out the solution using the rangesum function in combination with the aggr function.
That could be a rounding error. Perhaps the maketime function works better. Or perhaps you need to round or floor the values of Period too.
I take a completely different approach to rolling reports. I create an integer "Month Number" for the field. Since I work in a sales organization, our two most important rolling things are 12 mos rolling sales (e.g. sales for last twelve months), and 12 mos rolling forecast (e.g. forecast sales for next twelve months).
Forecast example: First, pick a base year that is outside (or at least, the earliest possible start) for your data. I use 2010 for the year, since we never have rolling forecasts or sales 5 years back!
Create a system variable vMonthNumberNow (vMNN for brevity) = (Year(today())-2010)*12+month(today())
For, say, Feb 2015, vMNN would be (2015-2010)*12+2=62 (Note the brackets in the expression!)
In my LOAD statement:
Calculate an absolute forecast month number, "AbsFMN", using the forecast close date:
(Year(ForecastClose)-2010)*12+Month(ForecastClose)
Calculate a relative forecast month number "RelFMN"
(Year(ForecastClose)-2010)*12+Month(ForecastClose)-$(vMNN)
Note that both AbsFMN and RelFMN are monotonically increasing integers.
Then, the next twelve months forecast is simply:
sum({$<[RelFMN]={">0<=12"}>} ForecastAmount) nb depending on your organization's rule, could be ">=0"
Year boundaries? Don't care! Trying to sort properly on "2012-Aug", "2012-Apr", etc? Don't care! This also lets me build 'waterfall' pivot tables - much beloved by my sales managers - by using either AbsFMN or RelFMN as the first dimension, and then sorting the horizontal (pivoted) dimension by the same field.
Well, I'm probably missing the point because I don't think it actually solves the problem I discussed above. Can you post an example load script and the expressions you use in a chart that shows a rolling 12 month sum for each month using a month field as one of the chart dimensions?
I have tried this code multiple times. It always crashes and freezes my entire machine. Its only doing 387,000 records so this should not be an issue. I have copied it directly from this post as
AsOfMonth:
load 'Current' as Type,
Month as Month_AsOf,
Month as Month
Resident SalesData;
Concatenate (AsOfMonth)
load 'Rolling 3' as Type,
Month as Month_AsOf,
Month + 1 - IterNo() as Month
Resident SalesData
while IterNo() <= 3;
right join load Month Resident SalesData;
I change SalesDate to the name of my Fact Table of Opportunities and set "Month" to the Month number of the Close Date but it crashes every time. I've tried other code examples from this site but they don't work either the results are never right. Rolling 3 and Rolling 6 , Rolling 12 all always have the same value so this can't be right.
Yes I have the same issue. This doesn't seem to work. It should not be so hard to create a 12 month Avg. My FY goes from Oct to Sep. So if in March and I want to go 12 months back it should be back to March of the Previous Fiscal Year. If I want to do an average by each month so it should be an accumulation of 12 Back from the current month displayed divided by 12. If in current month of March and I want to show Rolling Avg by month for 12 months back. My Chart should show each month Feb previous year to March current year. March should show (sum of Mar Previous Year to March current Year) /12, Feb shows( sum of Feb Previous Year to Feb current year)/12, Jan show (sum Jan Previous Year to Jan Current Year )/12 ...etc. I've been struggling with this for 2 weeks. Multiple code samples for ASOf_Table. Date Island etc. nothing yields the correct results needed. This is simple to do in excel why is Qlik so difficult?
Hello Susan,
Can you start a new discussion and upload a source data file (qvd, excel or csv) too? I'm sure we can help you find a solution.
Thanks Gysbert, Very Helpful Information
The main restriction with range functions is that businesses sometimes are seasonal and do not sell every month or day. Some businesses don't sell on Sundays, some don't sell on Christmas and some travel businesses don't sell in November when it's off season. In all that cases the range function does not return the last 3 month or the last 7 days but the last 3 or 7 periods with revenue. Therefor my favorite is the AsOf Table which precisely defines the periods in your data model.
Look also to this solution N-period rolling data, moving average, easy solution.