Forum Discussion

chris12345's avatar
chris12345
New Member
5 years ago
Solved

Order (count) based on distinct ID

Hi all,   I am quite new to the Power Query Editor. I've been trying to add an order/count based on an distinct ID like the example below.   ID |  ORDER | 1   |     1       | 1   |     2       ...
  • edhans's avatar
    5 years ago

    See if this works chris12345 

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlSK1UEljZBIY2xkLAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t]),
        #"Grouped Rows" = 
            Table.Group(
                Source, 
                {"ID"}, 
                {
                    {"Order", each Table.AddIndexColumn(_, "Order", 1, 1, Int64.Type)}
                }
        ),
        #"Expanded Order" = Table.ExpandTableColumn(#"Grouped Rows", "Order", {"Order"}, {"Order"}),
        #"Changed Type" = Table.TransformColumnTypes(#"Expanded Order",{{"Order", Int64.Type}})
    in
        #"Changed Type"

     

    It returns this.

    How to use M code provided in a blank query:
    1) In Power Query, select New Source, then Blank Query
    2) On the Home ribbon, select "Advanced Editor" button
    3) Remove everything you see, then paste the M code I've given you in that box.
    4) Press Done
    5) See this article if you need help using this M code in your model.

     

     

  • v-alq-msft's avatar
    5 years ago

    Hi, chris12345 

     

    Based on your description, I created data to reproduce your sceanrio. The pbix file is attached in the end.

    Table:

     

    You may apply the following transformations in Power Query. Here are the m codes in 'Advanced Editor'.

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlSK1UEljZBIY2xkLAA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ID = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}}),
        Custom1 = Table.Group(#"Changed Type",{"ID"},{"Order",(x)=> List.Generate(
        ()=>1,
        each _<=Table.RowCount(x),
        each _+1
       ) 
       }
    ),
        #"Expanded Order" = Table.ExpandListColumn(Custom1, "Order"),
        #"Changed Type1" = Table.TransformColumnTypes(#"Expanded Order",{{"Order", Int64.Type}})
    in
        #"Changed Type1"

     

    Result:

     

    Best Regards
    Allan

     

    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.