Elapsed duration

I am using Influx to track the state of machines in a manufacturing plant. States can be Running and Held.
I write a record when the state changes. E.g. when the machine starts, we write a record with state ‘Running’ and when the machine stops, we write a record with state ‘Held’.

I would like to write a query that returns the duration. Elapsed almost works, but gives the time to the previous record. I need the time to the next record. Is there any way to do this?

@geoff_at_spruik I think what you might be looking for is stateDuration(): https://docs.influxdata.com/flux/v0.36/functions/built-in/transformations/stateduration/