Forum Discussion
Looping (?) in Power BI
- 9 years ago
In the query editor (M / Power Query) you can achieve this without looping.
Steps to take:
Add 2 index columns: 1 starting with 0 and the other with 1 (Add Column - Index column).
Merge the table with itself such that you get the previous values for Fruit ID and Status on the same row as the current data
Sort on Index (as the merge disrupted the sort)
Add a custom column to determine the inital "Addition to Status": it will be "Rejected" if the previous status was "Rejected"and the Fruit Id is the same as the previous Fruit ID, otherwise if the fruit ID was changed it will be "" otherwise null.
Fill down this column, so "Rejected" will be filled down until the first non-null (= "" for each new fruit ID).
Remove columns that are no longer reuiqred.
The code below is illustrated with this video.
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"Fruit ID Number", Int64.Type}, {"Fruit Status", type text}}), #"Added Index" = Table.AddIndexColumn(#"Changed Type", "Index", 0, 1), #"Added Index1" = Table.AddIndexColumn(#"Added Index", "Index.1", 1, 1), #"Merged Queries" = Table.NestedJoin(#"Added Index1",{"Index"},#"Added Index1",{"Index.1"},"NewColumn",JoinKind.LeftOuter), #"Renamed Columns" = Table.RenameColumns(#"Merged Queries",{{"NewColumn", "Previous"}}), #"Expanded Previous" = Table.ExpandTableColumn(#"Renamed Columns", "Previous", {"Fruit ID Number", "Fruit Status"}, {"Previous.Fruit ID Number", "Previous.Fruit Status"}), #"Sorted Rows" = Table.Sort(#"Expanded Previous",{{"Index", Order.Ascending}}), #"Added Custom" = Table.AddColumn(#"Sorted Rows", "Addition to Status", each if [Previous.Fruit Status] = "Rejected" and [Previous.Fruit ID Number] = [Fruit ID Number] then "Rejected" else if [Fruit ID Number] <> [Previous.Fruit ID Number] then "" else null), #"Filled Down" = Table.FillDown(#"Added Custom",{"Addition to Status"}), #"Removed Columns" = Table.RemoveColumns(#"Filled Down",{"Index", "Index.1", "Previous.Fruit ID Number", "Previous.Fruit Status"}) in #"Removed Columns"
This is probably not the answer you are looking for but simply how I would approach it.
I would create a seperate data table with the id and status where the 'Fruit Status' is rejected
rename 'Fruit Status' in this table to 'Adition to Status'
then simply merge them together
if you dont want an 'Addition to Status' of rejected, when the 'Fruit Status' is rejected, and where 'Adition to Status' = 'Fruit Status' set the fruit status to blank.
Hope this is helps.
If your data source is SQL i would recommend doing that in SQL it would be probably be easier and quicker