Search code examples
powerbimeasure

Unexpected result of measure from filtering table with dynamic criteria in Power BI


I have a table called DW_XYZ:

Year Month Type Value
2021 1 A 10
2021 1 B 12
2021 2 A 20

*no data for type B in Month=2

I would like to create a measure that stores data that I already filtered by last month of data stored in DW_XYZ with dax formula:

CALCULATE( 
 SUM(DW_XYZ[Value]), 
 FILTER(DW_XYZ,DW_XYZ[Month]= 
 CALCULATE(MAX(DW_XYZ[Month]), 
 FILTER(DW_XYZ,DW_XYZ[Year]=
 MAX(DW_XYZ[Year]))) && DW_XYZ[Year]=MAX(DW_XYZ[Year]))

From the measure, I create 2 card visuals to display data of Type A and Type B each. 1st visual to display type A, so I drag the measure, and also drag column Type to 'visual filter' and manually select 'A', and do the same for 2nd visual (type B).

For type A, the card display expected value (of type A and Month=2). But for type B, the card display unexpected value (of type B and Month=1), it should be type B and Month=2 which is blank/zero. **btw, would be highly appreciated if the formula including blank value-handling to be zero (0) instead of blank.


Solution

  • Try

    MyMeasure =
    VAR MaxYear =
        CALCULATE ( MAX ( DW_XYZ[Year] ), ALL ( DW_XYZ[Type] ) )
    VAR MaxMonth =
        CALCULATE ( MAX ( DW_XYZ[Month] ), ALL ( DW_XYZ[Type] ) )
    RETURN
        0
            + CALCULATE (
                SUM ( DW_XYZ[Value] ),
                FILTER ( DW_XYZ, DW_XYZ[Year] = MaxYear && DW_XYZ[Month] = MaxMonth )
            )
    

    A crucial difference between the above and your attempt is the inclusion of ALL applied to the Type column as a filter for CALCULATE when determining the latest year and month. Without this, the external filter you are applying to the visual will force the evaluation to consider that Type only when determining those values.