Forum Discussion

JulieCooper's avatar
JulieCooper
Frequent Visitor
2 years ago
Solved

Index multiple subgroups

Hi,    I have a source document with columns A,B,C, and D, and I would like to automate the creation of the codes in columns E, F, and G with an Excel power query. My idea was to group and index th...
  • AlienSx's avatar
    2 years ago

    JulieCooper if your data is properly sorted then this should work (w/o Table.Group). If not sorted - sort them first. 

    let
        s = your_table,
        rows = List.Buffer(Table.ToRows(s)),
        cost_types = [SC = "1", LB = "2", MT = "3", PL = "4", OT = "5", SM = "6", RV = "7"],
        func = (prev, curr) => 
            curr & 
            {prev{4} + Number.From(prev{0} <> curr{0}),
            if prev{0} = curr{0} then prev{5} + Number.From(prev{1} <> curr{1}) else 1,
            if curr{2} = null then 0 else if {prev{0}, prev{1}} <> {curr{0}, curr{1}} then 1 else prev{6} + 1,
            Record.FieldOrDefault(cost_types, curr{3}, null)}, 
        gen = List.Generate(
            () => [i = 0, c = rows{0} & {1, 1, if rows{0}{2} = null then 0 else 1, Record.FieldOrDefault(cost_types, rows{0}{3}, null)}],
            (x) => x[i] < List.Count(rows),
            (x) => [i = x[i] + 1, c = func(x[c], rows{i})],
            (x) => x[c]
        ),
        tbl = Table.FromRows(gen, Table.ColumnNames(s) & {"Header Code", "Subheader Code", "Item Code", "Cost Type Code"}),
        cubit = Table.AddColumn(
            tbl, 
            "Cubit Code", 
            (x) => Text.From(x[Header Code]) & Number.ToText(x[Subheader Code], "00") &
                Number.ToText(x[Item Code], "00") & Text.From(x[Cost Type Code]) & x[Cost Type]
        )
    in
        cubit