Forum Discussion

Insert_Key's avatar
Insert_Key
Frequent Visitor
2 years ago
Solved

Need help restructuring a table (Pivot / Unpivot?)

Hi everyone 👋🙂   I was assigned a task right at the end of the day that feels so straightforward to me but I've just been chasing my tail on and it's doing my head in: I've been asked to transfor...
  • AlienSx's avatar
    AlienSx
    2 years ago

    Insert_Key my bad, I forgot that Table.FromRecords takes resulting columns from the very first record in the list. Then lets create tables from each group of data and combine them. Try this code. 

     

    let
        Source = Excel.CurrentWorkbook(){[Name="Table5"]}[Content],
        // function uses table column name to create a record of distinct values 
        fx = (tbl, col) => 
            [values = List.Distinct(Table.Column(tbl, col)),
            count = List.Count(values),
            names = if count = 1 then {col} else List.Transform({1..count}, (x) => col & " " & Text.From(x)),
            out = Record.FromList(values, names)][out],
        // column names - you may filter unwanted columns
        columns = List.Buffer(Table.ColumnNames(Source)),
        // control "group by" list, now it produces OUTPUT B from your sample. To get OUTPUT A use {"NAME"}
        to_rows = Table.Group(
            Source, 
            {"NAME", "ID"}, 
            {"x", (x) => Table.FromRecords(
                {Record.Combine(List.Transform(columns, (w) => fx(x, w)))}
            )}),
        to_table = Table.Combine(to_rows[x])
    in
        to_table