'Calculate the difference between two groups for a time series

I'm using Influxdb version 1.18.

I have a measurement x with different type. x is always increasing. I'm looking for a way to determine the increment of x over the last 15 min for type 'A' and 'B' and their difference.

I'm stuck at this.

SELECT A, B, A - B AS C
FROM (
  SELECT difference(last(value)) AS A
  FROM x
  WHERE type = 'A'
  GROUP BY time(15m)
),
(
  SELECT difference(last(value)) AS B
  FROM x
  WHERE type = 'B'
  GROUP BY time(15m)
)

Which yields

time                A        B     C
----                -------- ----- ---
1650171600000000000          0.024     
1650171600000000000 0.252              
1650172500000000000          0.04      
1650172500000000000 0.232              

I'd like to get the output below from a continuous query.

time                A        B     C
----                -------- ----- ---
1650171600000000000 0.252    0.024 0.228
1650172500000000000 0.232    0.04  0.192    


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source