Forum Discussion

JessQA's avatar
JessQA
Frequent Visitor
9 years ago
Solved

Looping (?) in Power BI

Hi Everyone,   I was hoping someone could help me with a part of the formula to get me to my end goal.   Basically, I want to create a new column in Power BI that says IF column D has "Rejected" ...
  • MarcelBeug's avatar
    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"