Forum Discussion
Refer to row for a new column
- 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"
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"
yes, agree that generally speaking power query is better, because it can scale up to larger datasets. DAX option may run into performance issues.