Subtract _value of first record from _value of last record in a table

I’m very new to InfuxDB and I’m struggling to write a query in flux that returns the difference between the “_value” fields of the first and the last record in my table. Any help?

@Vasu_Yadav If the values in your table only increment up, you can just use spread().

  |> spread()

If they fluctuate up and down throughout the table and there’s a chance the last value is less that other values in the table, you can use reduce() to create a custom aggregate that only subtracts the first value from the last value:

  |> reduce(
    identity: {index: 0, first: 0.0,  _value: 0.0},
    fn: (r) => ({
      index: accumulator.index + 1,
      first: if accumulator.index == 0 then r._value else accumulator.first,
      _value: if accumulator.index !=0 then r._value - accumulator.first else 0.0
1 Like