Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
2 years ago
Solved

Refer to row for a new column

I have a table with the first 4 columns and I would like to create the last column. What is the best way to go about this?    I have seen people use rank but will this work when I have more and mor...
  • BenjaminSNN's avatar
    2 years ago

    Hey!

    I think this is best done by adding a custom column in Power Query.
    Basically you create a unique ID based on ID-Year-Month and a ID for previous month ID-Year-(Month -1) then you can join the query with itself to get values from the previous month within that ID.

    Code:

    let
    Source =YOURSOURCE,
     #"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"Year", Int64.Type}, {"Month", Int64.Type}, {"Quantity 1", Int64.Type}}),
    #"+ TempId" = Table.AddColumn(#"Changed Type", "TempID", each Text.From([ID]) & "-" & Text.From([Year]) & "-" & Text.From([Month])),
    #"+ TempId_prev" = Table.AddColumn(#"+ TempId", "TempId_prev", each Text.From([ID]) & "-" & Text.From([Year]) & "-" & Text.From([Month] - 1)),
    #"Self-join" = Table.NestedJoin(#"+ TempId_prev", {"TempId_prev"}, #"+ TempId_prev", {"TempID"}, "Added Custom", JoinKind.LeftOuter),
    #"Expanded Added Custom" = Table.ExpandTableColumn(#"Self-join", "Added Custom", {"Quantity 1"}, {"Prior Month Quantity 1"}),
    #"Replaced Value" = Table.ReplaceValue(#"Expanded Added Custom",null,0,Replacer.ReplaceValue,{"Prior Month Quantity 1"}),
    #"Sorted Rows" = Table.Sort(#"Replaced Value",{{"TempID", Order.Ascending}}),
    #"Removed Columns" = Table.RemoveColumns(#"Sorted Rows",{"TempID", "TempId_prev"})
    in
    #"Removed Columns"