How to reference dynamic column names in Power Query (M language)

5.3k Views Asked by At

Table columns and static M code

I was wondering if the there is a way to reference these three columns to create a summed column even though they change names?

The three columns vary depending on what quarter the underlying query in ran for (1-4)

The issue is when it runs for any quarter other than the one that was in the query when the table was created the addition column breaks because it can't find the columns named January, February, and March (because they are now 3 different months).

2

There are 2 best solutions below

0
Wedge On BEST ANSWER

If you know all of the columns that won't change, you can refer to the record with all of the fixed columns removed from it, so you'll just be adding up your dynamic columns. The code looks like this (where you place the name of your fixed columns in the list).

List.Sum(Record.ToList(Record.RemoveFields(_, {"Fixed", "Column", "Name"})))
0
JMcD On

The accepted answer is great and got me on the right path with pretty much the same problem. I learned a couple of things I want to pass along.

  1. You don't need to remove fixed fields. You can use Record.SelectFields.
  2. Without buffering the dynamic field name list, there can be a significant performance penalty as it reloads the field name list for every record.

This is what I landed on:

List.Sum(Record.ToList(Record.SelectFields(_, List.Buffer(PreviouslyDefinedColumnNameList))))