Rank Within Group in Power Query M

Ranks rows within each group by a numeric column, highest value first.

Table TransformationsAdvancedrankgroupsortreshape

Power Query M code

let
    Source = YourTable,
    Grouped = Table.Group(Source, {"GroupColumn"}, {{"AllRows", each Table.AddIndexColumn(Table.Sort(_, {{"Value", Order.Descending}}), "Rank", 1, 1, Int64.Type), type table}}),
    Expanded = Table.ExpandTableColumn(Grouped, "AllRows", Table.ColumnNames(Source) & {"Rank"})
in
    Expanded

Notes

Change Order.Descending to Order.Ascending to rank lowest-first.

Requirements

How to use this snippet

  1. In Power BI Desktop, choose Transform data to open Power Query, then open the Advanced Editor on a query (or start from a blank query).
  2. Paste the snippet and replace the placeholder names (tables, columns, file paths) with your own. Check the requirements above first.
  3. Run it through the Power Query M Formatter to tidy the layout.

Related Power Query M snippets

More Power Query M resources

Browse all 145 snippets in the Power Query M Code Snippets, or search the library for something similar to Rank Within Group.