Forum Discussion

androo's avatar
androo
Advocate III
3 years ago
Solved

Flatten Parent Child Hierarchy

hello,   I am looking to get the following result (P is Parent, C is Child).   P_ID P_Name2 C_ID_1 C_ID_2 C_ID_3 C_ID_4 C_Name_1 C_Name_2 C_Name_3 C_Name_4 1 One 264       A ...
  • AlienSx's avatar
    3 years ago

    Hello, androo 

    let
        Source = your_table,
        f = (tbl as table) =>
            [count = Table.RowCount(tbl),
            lst = List.Buffer(List.Transform({1..count}, Text.From)),
            ids = Record.FromList(tbl[C_ID], List.Transform(lst, (x) => "C_ID_" & x)),
            names = Record.FromList(tbl[C_Name], List.Transform(lst, (x) => "C_Name_" & x)),
            res = [id = ids, name = names]][res],
        g = Table.Group(Source, {"P_ID", "P_Name"}, {{"all", f}}),
        expand = Table.ExpandRecordColumn(g, "all", {"id", "name"}),
        id_cols = List.Distinct(List.Combine(List.Transform(expand[id], Record.FieldNames))),
        name_cols = List.Distinct(List.Combine(List.Transform(expand[name], Record.FieldNames))),
        expand_id = Table.ExpandRecordColumn(expand, "id", id_cols),
        expand_name = Table.ExpandRecordColumn(expand_id, "name", name_cols)
    in
        expand_name