Forum Discussion

OscarSuarez10's avatar
OscarSuarez10
Icon for Helper III rankHelper III
7 years ago
Solved

Add index per proudct and year using power query

Hello How can I add an Index column using power query that starts in 0 like in the following table?

 

ProductYearIndex
A20190
A20201
A20212
A20223
B20190
B20201
B20212
B20223
C20190
C20201
C20212
C20223
  • v-piga-msft's avatar
    v-piga-msft
    7 years ago

    Hi OscarSuarez10 ,

    You could try the query below.  You need to group rows by Product and then create the custom column.

    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("TcuxCQAwCADBXawt1C5ldAxx/zUCgYQvr7hu2aIS5ktGH8IIJ+IieZIneZKneIqneOqfOQ==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [Product = _t, Year = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Product", type text}, {"Year", Int64.Type}}),
        #"Grouped Rows" = Table.Group(#"Changed Type", {"Product"}, {{"all", each _, type table [Product=text, Year=number]}}),
        #"Added Custom" = Table.AddColumn(#"Grouped Rows", "Custom", each Table.AddIndexColumn([all], "SubCount",0,1)),
        #"Removed Columns" = Table.RemoveColumns(#"Added Custom",{"all"}),
        #"Expanded Custom" = Table.ExpandTableColumn(#"Removed Columns", "Custom", {"Year", "SubCount"}, {"Custom.Year", "Custom.SubCount"})
    in
        #"Expanded Custom"

    Here is the output.

    Best Regards,

    Cherry

     

5 Replies

  • HotChilli's avatar
    HotChilli
    Icon for Community Champion rankCommunity Champion

    Add an Index (from 0) call it IndexFromZero

    Add a custom column with:

    Number.Mod([IndexFromZero],4))
    • OscarSuarez10's avatar
      OscarSuarez10
      Icon for Helper III rankHelper III

      Sorry but when is 2019 I need that it appears Inex = 0 because is the first year and the same for 2020 = 1, 2021 = 2 and so on,  and I got this:

       

       

      • HotChilli's avatar
        HotChilli
        Icon for Community Champion rankCommunity Champion

        The code I posted works for the data you provided.

        It depends on the data being in a similar order to your sample.

        Do you want to post the real data OR if you want, just write a simple IF statement

        if Year = 2019 then 0 else if Year = 2018 then...........

         

        make sure you change the data type of Year to number before adding the column