powerbipowerquerym

Reference a column by a variable


I want to reference a table column by a variable while creating another column but I can't get the syntax:

    t0 = Table.FromRecords({[a = 1, b = 2]}),
    c0 = "a", c1 = "b",
    t1 = Table.AddColumn(t0, "c", each([c0] + [c1]))

I get the error the record's field 'c0' was not found. It is understanding c0 as a literal but I want the text value contained in c0. How to do it?

Edit

I used this inspired by the accepted answer:

    t0 = Table.FromRecords({[a = 1, b = 2]}),
    c0 = "a", c1 = "b",
    t1 = Table.AddColumn(t0, "c", each(Record.Field(_, c0) + Record.Field(_, c1)))

Solution

  • Another way:

    let
        t0 = Table.FromRecords({[a = 1, b = 2]}),
        f = {"a","b"},
        t1 = Table.AddColumn(t0, "sum", each List.Sum(Record.ToList(Record.SelectFields(_, f))))
    in
        t1