Forum Discussion
Calculate difference between two rows
Hi supermulder,
It depends on your needs, if you measure is "context filter" depend, you should you MattAllington DAX solution.
If not, you can also precalc the diff at leaf level with Power Queery by implementing running total techniques with Power Query :
1. Create you data source query (for example SampleDataSource), order you data by "date" column, add a first index starting by 1, add a second index called previous index starting by 0 and modify your query in order to create only connection . You should have this M code :
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMjIwNNM1MNI1NFDSUTI0MDBQitVBEjUEiRqhixqBRE1BorEA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type text) meta [Serialized.Text = true]) in type table [Date = _t, Value = _t]),
#"Change type" = Table.TransformColumnTypes(Source,{{"Date", type date}, {"Value", Int64.Type}}),
#"Order rows" = Table.Sort(#"Change type",{{"Date", Order.Ascending}}),
#"Add index started by 1" = Table.AddIndexColumn(#"Order rows", "Index", 1, 1),
#"Add index started by 0" = Table.AddIndexColumn(#"Add index started by 1", "Previous Index", 0, 1)
in
#"Add index started by 0"
2. Create a new query by Referecing the first one (for example Sample). Merge the 2 queries with left join by using Sample.Previous Index = SampleDataSource.Index. Expand the referenced table to get the value, calc the diff and remove all temp columns. Finally, you should have this M Code :
let
Source = SampleDataSource,
#"Merge queries" = Table.NestedJoin(Source,{"Previous Index"},SampleDataSource,{"Index"},"Previous",JoinKind.LeftOuter),
#"Previous expdanded" = Table.ExpandTableColumn(#"Merge queries", "Previous", {"Value"}, {"Previous.Value"}),
#"Add custom column Diff" = Table.AddColumn(#"Previous expdanded", "Diff", each [Value] - [Previous.Value]),
#"Delete temp columns" = Table.RemoveColumns(#"Add custom column Diff",{"Index", "Previous Index", "Previous.Value"})
in
#"Delete temp columns"
Just use diff column on your visuals.