excelpivot-table

Show Difference in max/min values within Pivot Table?


I am trying to add a column in a Pivot Table, that shows the difference between the max and min values within a row/field.

Sample Data:

Name           State    Value
Albert          MA      1
Albert          MA      2
Albert          TX      3
Brittney        CA      5
Brittney        CA      3
Brittney        CA      2
Brittney        CA      1
Franklin        AL      3
Franklin        AL      2
Franklin        AL      3
Franklin        AL      4
Franklin        NV      4
Franklin        AK      9
Franklin        MO      2

And my simple pivot table is below. For each Name, I'm trying to calculate the difference in the largest and smallest value per the "State" rows. I've added a manual column, "Largest Distance" to show what I'd like to return.

Where there's a single value, return 0 since there's no max/min. Otherwise, max(Value)-min(value) is what I'm looking for. The "Avg Value" column is a calculated field where the formula is =max(Value)-min(Value), but it shows 0 for everything, even when I change to show the SUM, or Average, or Count, etc.

pivot table example (The 7 is from 9-2)


Solution

  • Load your data into the data model. (I'll assume a table called Table1)

    Create a measure for the average called Avg Value using:

    =AVERAGE(Table1[Value])

    Create another measure for the difference value you want using something like:

    =IF(ISFILTERED(Table1[State]),
       BLANK(),
       VAR __stateVals = ADDCOLUMNS(SUMMARIZE(ALLEXCEPT(Table1,Table1[Name]),Table1[State]),"AvgVal",[Avg Value])
       RETURN MAXX(__stateVals,[AvgVal])-MINX(__stateVals,[AvgVal]))
    

    which should give you this:

    enter image description here