Averaging values over time period and then identifying the max value in each time period

Hello,

I have data points that are captured approximately every second from 5 different devices. I want to get the average value for each device every two seconds and then from this identify the device with the highest value every two seconds. It’s important that I average the data first as it has an inherent variability before establishing which device had the highest value in each two second period.

The following query works well to average the captured data and provide a value for each two second interval:

from(bucket: "Mogumber 80 pig pilot")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => r["_measurement"] == "x")
  |> filter(fn: (r) => r["_field"] == "r")
  |> filter(fn: (r) => r["d"] == "24EC")
  |> filter(fn: (r) => r["g"] == "3CC0" or r["g"] == "7CFC" or r["g"] == "5AE0" or r["g"] == "59CC" or r["g"] == "3DD4")
  |> aggregateWindow(every: 2s, fn: mean, createEmpty: false)

However, I’m not sure how to proceed from here where I want to identify which device (g) has the highest average value (r) every 2 seconds.

Can anyone please offer some guidance here for someone who is new to Flux?