简体   繁体   中英

Rolling average a certain period using a DAX measure in Power BI

I tried generating a DAX measure as a rolling average. I don't quite know how to insert the measure I need rolling averaged as "CPI_annualized". It is not giving an option to bring CPI_annualized into the Rolling Average calc.

This is the error I am given when trying to construct the RollingAverage VAR in the measure P_MA

The syntax for 'CALCULATE' is incorrect. DAX(VAR __LAST_DATE = LASTDATE('public econometrics'[date]) ...... 

This is the DAX measure that I am trying to complete:

    P_MA = 
VAR __NUM_PERIODS = 3
VAR __LAST_DATE = LASTDATE('public econometrics'[date])
VAR RollingAverage =
    AVERAGEX(
         DATESBETWEEN(
            'public econometrics'[date],
            DATEADD(__LAST_DATE, -__NUM_PERIODS, MONTH),
                __LAST_DATE)
            CALCULATE([CPILFESL]))
)
RETURN RollingAverage

This is the DAX measure that I am trying to use in the rolling calculation with the data in my dB given monthly. This works as below.

CPI_annualized = (CALCULATE(SUM('public econometrics'[value]),'public 
econometrics'[econometric_name]=="CPILFESL")/CALCULATE(SUM('public 
econometrics'[value]),'public 
econometrics'[econometric_name]=="CPILFESL",SAMEPERIODLASTYEAR('public econometrics'[date])))-1

Inserting this measure in a line chart gives my this table.

date CPILFESL
1 January, 1978 6.41%
1 February, 1978 6.20%

I think you are getting error message due to this line:

CALCULATE([CPILFESL])

In Dax Calculate measure, you cannot directly calculate a value, instead you have to include a number calculation function such as sum, max, min, here is the example:

CALCULATE(sum([CPILFESL]))

In addition, you can get rid of Calculate measure when there is no filter expression, such as sum([CPILFESL]) is enough.

A proper way of using calculate is to filter the value, as shown in online documentation

CALCULATE(
    SUM(Sales[Sales Amount]),
    'Product'[Color] = "Blue"
)

You can find many usefull templated here:

https://www.daxpatterns.com/month-related-calculations/

Moving average 3 months

VAR MonthsInRange = 3
VAR LastMonthRange =
    MAX ( 'Date'[Year Month Number] )
VAR FirstMonthRange =
    LastMonthRange - MonthsInRange + 1
VAR Period3M =
    FILTER (
        ALL ( 'Date'[Year Month Number] ),
        'Date'[Year Month Number] >= FirstMonthRange
            && 'Date'[Year Month Number] <= LastMonthRange
    )
VAR Result =
    IF (
        COUNTROWS ( Period3M ) >= MonthsInRange,
        CALCULATE (
            AVERAGEX ( Period3M, [Sales Amount] ),
            REMOVEFILTERS ( 'Date' )
        )
    )
RETURN
    Result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM