Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Earn a 50% discount on the DP-600 certification exam by completing the Fabric 30 Days to Learn It challenge.

Reply
boley2131
Frequent Visitor

Calculating Monthly Average Over 5 years with Context

I'm about to pull my hair out and could use some help 😁

 

I'm working on a report where I want to show a comparison of monthly sales versus the 5yr average for that given month.  I've gotten the calculation to work, but the problem I'm facing is that I want the calculation to work when the date filter context is less than 5 years as well.  For example, I want the 5 year average of the month to work correctly when there is less than 5 years within the filter context.

 

Below is a look at a subset of my data where there is a row for each year/month:

YearMonthShortIndustry Units
2023Jun303
2023May536
2023Apr1019
2023Mar974
2023Feb627
2023Jan651
2022Dec648
2022Nov247
2022Oct806
2022Sep340
2022Aug274
2022Jul447
2022Jun401
2022May700
2022Apr1163
2022Mar832
2022Feb491
2022Jan484
2021Dec569
2021Nov149
2021Oct346
2021Sep96
2021Aug84
2021Jul135
2021Jun268
2021May400
2021Apr913
2021Mar824
2021Feb471
2021Jan495

 

Below is the DAX code that I'm using which calculates the 5year average perfectly. 

 

Industry Units 5yr Avg 2 = 
VAR EndDate =
    MAX( 'Date'[Date] ) -- retrieves MAX Date   
VAR StartDate =
    EDATE( EndDate, -59 )  -- shifts EndDate to year beginning
VAR Result =
    AVERAGEX(
        CALCULATETABLE(
                SUMMARIZE('Date', 'Date'[Year], 'Date'[MonthName]),
                DATESBETWEEN('Date'[Date], StartDate, EndDate)
                ),
        'Measures Industry'[Industry Units])        
RETURN Result

 

 

Unfortunately, when a filter is applied on the date table the calculation pulls back the lastest month value.

Any help would be apprecited!

Thanks!

 

2 REPLIES 2
sergej_og
Super User
Super User

Just an idea.
Maybe with a small adjustment for VAR Result like this: so you will have a running AVG at the end.

VAR MaxDate = MAX('Calendar'[Date])
VAR Result = CALCULATE(
                AVERAGEX(
                    VALUES('Calendar'[MonthInCal]), [Sum Industry Units Measure]),
                    DATESINPERIOD('Calendar'[Date], MaxDate, -5, YEAR)
            ) 
--MonthInCall looks like this Jan 2019, Feb 2019... and so on

sergej_og_0-1694731730044.png

Maybe you have to create new calendar column.

sevenhills
Super User
Super User

Try changing this and see if it works

 

 

 

VAR EndDate = SELECTEDVALUE( 'Date'[Date] , MAX( 'Date'[Date] ) -- retrieves MAX Date   
                )

 

 

 

 

Helpful resources

Announcements
PBI_APRIL_CAROUSEL1

Power BI Monthly Update - April 2024

Check out the April 2024 Power BI update to learn about new features.