How to get total duration of state?

I want to calculate machine running hours based on his state stored in influx DB.
Question is how to retrive total duration of a value from influxDB with flux query?
The grafana can nice show the state timeline > grafana state timeline
I look for the sum of the time duration where the value is equal == "Run" od only equal to number == 2.
Can you help me please.

You should be able to use the integral function. What values does the run field have?

Hi Colin.

Value 2 = Run
Value 1 = Stup

This are manual pushed data for testing.

In grafana is posible to make nice graph with state history.
But what I need is to have the sum of each state.

I assumed that you were storing the state regularly, in which case I think it is fairly easy, but it looks as if you are only saving it on change. Is that correct? If so then I don't know how to do that direct via a query. You could do it in node-red of course by fetching the data and calculating the answer.