Forum Discussion

olena2212's avatar
olena2212
Frequent Visitor
2 years ago
Solved

Numbers reconciliation in PowerQuery with M language

Hello everyone,   i need to reconcile numbers in powerquery within specific vendor name (to link the rows to each other and then i will filter out the paired rows which result to zero), so that i o...
  • AlienSx's avatar
    2 years ago

     

    let
        Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
        rows = List.Buffer(Table.ToRows(Source)),
        f = (s, c) =>
            [a = s{0},
            match = List.Select(s, (x) => {a{1}, a{2}} = {x{1}, -x{2}}){0}? ?? {},
            upd_c = if List.IsEmpty(match) 
                then c & {a} 
                else c & {a & {match{0}}} & {match & {a{0}}},
            upd_s = List.RemoveMatchingItems(s, {a, match}),
            next = if List.IsEmpty(s) 
                then c
                else @f(upd_s, upd_c)][next],
        upd_rows = f(rows, {}),
        z = Table.FromList(upd_rows, (x) => x, Table.ColumnNames(Source) & {"Linked ID"}, null)
    in
        z

     

  • slorin's avatar
    2 years ago

    Hi, olena2212 AlienSx , dufoq3 

     

    Another solution with Table.Group

     

    let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    Abs = Table.AddColumn(Source, "Abs", each Number.Abs([Amount])),
    Group = Table.Group(Abs, {"Vendor name", "Abs"},
    {{"Data", (x) => let
    positive = Table.ToColumns(Table.SelectRows(x, each [Amount]=[Abs])),
    negative = Table.ToColumns(Table.SelectRows(x, each [Amount]=-[Abs])),
    data = Table.FromColumns(positive & {negative{0}}, Table.ColumnNames(Abs) & {"Linked ID"}) &
    Table.FromColumns(negative & {positive{0}}, Table.ColumnNames(Abs) & {"Linked ID"})
    in data}}),
    Result =
    Table.Sort(
    Table.SelectRows(
    Table.RemoveColumns(
    Table.Combine(Group[Data]),
    {"Abs"}),
    each [Id]<>null),
    {{"Id", Order.Ascending}})
    in
    Result

    Stéphane