I'd like to calculate the time difference between a value in Bi and Bi+1, in PowerBI. That is, in a new a column, in the Query Editor (so writing in M), I want to have:
C3 = B3-B2
C4 = B4 - B3
and so on.
Do you know how to achieve this in PowerBI?
You can use a calculated column like the below to compare each row against the previous then compute the difference in seconds using the DATEDIFF
function:
Difference in Seconds =
DATEDIFF (
'Table'[Time],
CALCULATE (
MIN ( [Time] ),
FILTER ( ALL ( 'Table' ), [ID] < EARLIER ( 'Table'[ID] ) )
),
SECOND
)
If you want to compare it against the previous ID time value, regardless if the time value is higher you can simply use:
Difference in Seconds =
DATEDIFF (
'Table'[Time],
CALCULATE (
MIN ( [Time] ),
FILTER ( ALL ( 'Table' ), [ID] = EARLIER ( 'Table'[ID] ) - 1 )
),
SECOND
)
Using LOOKUPVALUE
:
Difference in Seconds =
DATEDIFF (
'Table'[Time],
LOOKUPVALUE ( 'Table'[Time], 'Table'[ID], [ID] - 1 ),
SECOND
)
UPDATE: Adding the column from source via M Language.
Use something like this in a custom column:
=Table.AddColumn(#"YourLastStep", "Diff",
each
(try DateTime.From(#"YourLastStep"[Time]{[ID]-2})
otherwise DateTime.From([Time])) - [Time]
)
Hope it helps.