Forum Discussion
Calculating Difference from Previous Row
You can do this all in Power Query
- Group by Unique ID
- For each subgroup
- Add an shifted (offset) Grade value column
- (more efficient subtraction than using an Index column)
- Subtract the Shifted Grade Value from the Gr ade Value
- Add an shifted (offset) Grade value column
- Re-expand the table
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjQyNlHSUQJhx9KS0tw8BUOlWB24uDlC3AhZ3BSIgwuKMvPSoepNzcwtgGKGRugGwSRM0E1ClkAxytLQwNAQ1W6cEkYoEhYoRsUCAA==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [#"Unique ID" = _t, #"Grade Value" = _t, #"Half Term" = _t]),
#"Changed Type" = Table.TransformColumnTypes(Source,{{"Unique ID", Int64.Type}, {"Grade Value", Int64.Type}, {"Half Term", type text}}),
#"Grouped Rows" = Table.Group(#"Changed Type", {"Unique ID"}, {
{"Half Termly Changes", (t)=>
let
//add shifted grade value column
//Then subtract from grade value
#"Shifted Grade Value" = Table.FromColumns(
Table.ToColumns(t)
& {{null} & List.RemoveLastN(t[Grade Value])},
type table[Unique ID=nullable number, Grade Value=nullable number, Half Term=nullable text, Shifted Grade Value=nullable number]),
#"Change" = Table.AddColumn(#"Shifted Grade Value","Half Termly Change", each [Grade Value] - [Shifted Grade Value], type nullable number),
#"Remove Shifted" = Table.RemoveColumns(#"Change",{"Shifted Grade Value"})
in
#"Remove Shifted",
type table [Unique ID=nullable number, Grade Value=nullable number, Half Term=nullable text, Half Termly Changes=nullable number]}}),
#"Expanded Half Termly Changes" = Table.ExpandTableColumn(#"Grouped Rows", "Half Termly Changes", {"Grade Value", "Half Term", "Half Termly Change"})
in
#"Expanded Half Termly Changes"Results
Hi, thank you for your response to this.
As stated before I am fairly new to Power BI - I know how to Group by a column (and then re-expand it) but please could you explain how I would add a shifted Grade Value column? Is this done within the Group By window?
For the Subtraction, I am assuming this is a simple Column A - Column B calculation?
- ronrsnfld3 years agoSuper User
You need to do it in the advanced editor of the power query user interface. From Power BI select transform data. In the left hand column, select a new query from blank. From the home tab, select advanced editor. Then paste the code above into the window that opens in place of what is already there. You can then examine the code and the applied steps to better understand the process.