Forum Discussion

Tom_G's avatar
Tom_G
Helper II
4 years ago
Solved

Index by subgroups with repeated values

Hello,   I have a dataset like the below.   Van number Calling ID Index 133456 1345 1 133456 1346 2 133456 1347 3 133456 1347 3 133456 1347 3 133457 1348 1 1...
  • serpiva64's avatar
    4 years ago

    Hi,

    this reply is inspired by the article –

    Dense Ranking with Power Query – Unexpected Behavior and Workarounds 

    written by wmfexcel

     

    and by the article:

    Nested Calculations In Power Query

    written by Chris Webb.

     

    to obtain this:

    You need:

    - first create a query in which you remove duplicates and rank 

    let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjQ2NjE1U9IBMkxMQZRSrA6qKIgywhA1B1LG5ImaQ0QtUG2Dilqi2oYqGgsA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Van number" = _t, #"Calling ID" = _t, Index = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Van number", Int64.Type}, {"Calling ID", Int64.Type}, {"Index", Int64.Type}}),
    #"Removed Columns" = Table.RemoveColumns(#"Changed Type",{"Index"}),
    #"Removed Duplicates" = Table.Distinct(#"Removed Columns", {"Calling ID"}),
    #"Grouped Rows" = Table.Group(#"Removed Duplicates", {"Van number"}, {{"AllRows", each _, type table [Van number=nullable number, Calling ID=nullable number]}}),
    RankFunction = (tabletorank as table) as table =>
    let
    SortRows = Table.Sort(tabletorank,{{"Calling ID", Order.Ascending}}),
    AddIndex = Table.AddIndexColumn(SortRows, "Rank", 1, 1)
    in
    AddIndex,
    //Apply that function to the AllRows column
    AddedRank = Table.TransformColumns(#"Grouped Rows", {"AllRows", each RankFunction(_)}),
    #"Expanded AllRows" = Table.ExpandTableColumn(AddedRank, "AllRows", {"Calling ID", "Rank"}, {"Calling ID", "Rank"})
    in
    #"Expanded AllRows"

     

    - then in the original query (the one where you have duplicates) you have only to merge the second one:

     let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjQ2NjE1U9IBMkxMQZRSrA6qKIgywhA1B1LG5ImaQ0QtUG2Dilqi2oYqGgsA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Van number" = _t, #"Calling ID" = _t, Index = _t]),
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Van number", Int64.Type}, {"Calling ID", Int64.Type}, {"Index", Int64.Type}}),
    #"Removed Columns" = Table.RemoveColumns(#"Changed Type",{"Index"}),
    #"Merged Queries" = Table.NestedJoin(#"Removed Columns", {"Calling ID"}, RemovedDuplicates, {"Calling ID"}, "Table (3)", JoinKind.LeftOuter),
    #"Expanded Table (3)" = Table.ExpandTableColumn(#"Merged Queries", "Table (3)", {"Rank"}, {"Rank.1"})
    in
    #"Expanded Table (3)"

     

    and that's done