powerbi

Calculate average of 2 columns ignoring zeros


I have 2 columns in a table UPS as follows

Location    1st Service Age  2nd Service Age
town1       3                0
town2       5                2
town3       6                0
town4       0                0
town5       2                1

How can I calculate (measure) the average age of both columns, ignoring 0's and slicer. For the above the answer should be 19/6 = 3.17, if all zeros, give 0.00

Thank you in advance


Solution

  • There's quite a few ways to do this, but here's probably the easiest to follow. You'll need three calculations against your table. These could all be conducted in one measure or broken out individually, as shown below:

    Total_Sum

    Total_Sum = SUM('UPS'[1st Service Age]) + SUM('UPS'[2nd Service Age])
    

    Non_Zero_Count

    Non_Zero_Count = 
    SUMX(
        'UPS',
        IF('UPS'[1st Service Age] = 0, 0, 1) + IF('UPS'[2nd Service Age] =0, 0, 1)
    )
    

    AVG_AGE

    AVG_AGE = if([Non_Zero_Count]=0,0,
        DIVIDE([Total_Sum], [Non_Zero_Count]))
    

    or combined to single measure

    singleCalc = 
    VAR Total_Sum = SUM('UPS'[1st Service Age]) + SUM('UPS'[2nd Service Age])
    VAR Non_Zero_Count = 
    SUMX(
        'UPS',
        IF('UPS'[1st Service Age] = 0, 0, 1) + IF('UPS'[2nd Service Age] =0, 0, 1)
    )
    RETURN
    if(Non_Zero_Count=0,0,Total_Sum/Non_Zero_Count)
    

    Demonstration of results in Power Bi application