Search code examples
powerquerym

Conditional averages (AVERAGEIF) in PowerQuery (M)


I have this table:

Month     Group     Value
  1         A        100
  2         A        115
  3         A        125
  1         B        200
  2         B        215
  3         B        225

I am trying to create a new (fourth) column which contains the quarterly averages, hence does something similar to AVERAGEIF exist in Power Query? The result should look like this:

Month     Group     Value     Average
  1         A        100       113.3
  2         A        115       113.3
  3         A        125       113.3
  1         B        200       213.3
  2         B        215       213.3
  3         B        225       213.3

Apologies for not providing a MWE.


Solution

  • Use code below; no merge necessary. Alexis Olson method will work best for large data sets

    let Source= #table({"Month", "Group","Value"}, {{1,"A",100},{2,"A",115},{3,"A",125},{1,"B",200},{2,"B",215},{3,"B",225}}),
    AvgAmount = Table.AddColumn(Source, "Average", (i) => List.Average(Table.SelectRows(Source, each [Group] = i[Group])[Value]), type number)
    in AvgAmount
    

    enter image description here