Saturday, November 4, 2023

How to Repeat Rows in a Table and Add Index in Power Query

How to Repeat Rows based on a Column and Add Index in Power Query
Scenario:
Suppose we have the sample data as follows:

Now from above data, based on the [Freq] column, we have to repeat the rows and add Index.
Eg: 
If [Freq] =3 then we have to repeat that row for 3 times and then need to add a Index column with values as 1,2,3.

We can achieve this Scenario, using the following M-Query:
let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("Zc3bCQAhDETRXvItmInxVYvYfxuyGwNL9m/gwNy1CFKUEgFZszD42bTTC9WgOohDM2gOxaEbdAd1GAbj15gGM14pG4BjXXEFsaJyRT6ZfQA=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [ProdID = _t, DateKey = _t, Freq = _t]),

ChangeType = 
Table.TransformColumnTypes(Source,{{"ProdID", Int64.Type}, {"DateKey", type date}, {"Freq", Int64.Type}}),

RepeatRowsIndex
Table.AddColumn(ChangeType, "tempField", each 
Table.AddIndexColumn(
Table.Repeat(Table.FromRecords({[temp=null]}),[Freq]),"Index",1,1, Int16.Type)),

ExpandRows = Table.ExpandTableColumn(RepeatRowsIndex, "tempField", {"Index"}, {"Index"})

in
    ExpandRows

Result:

Thanks, TAMATAM

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog