# Aggregate window with dynamic every based on total points

**URL:** <https://community.influxdata.com/t/aggregate-window-with-dynamic-every-based-on-total-points/24368>\
**Category:** Fluxlang\
**Tags:** influxdb\
**Created:** [March 23, 2022, 2:02pm UTC](https://community.influxdata.com/t/aggregate-window-with-dynamic-every-based-on-total-points/24368 "2022-03-23T14:02:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Eto](https://avatars.discourse-cdn.com/v4/letter/e/e19b73/32.png) [@Eto](https://community.influxdata.com/u/Eto)\
**Post date:** [March 23, 2022, 2:02pm UTC](https://community.influxdata.com/t/aggregate-window-with-dynamic-every-based-on-total-points/24368/1 "2022-03-23T14:02:53Z")

</div>

Is there any easy way to do a dynamic aggregatewindow based of total data points returned in a query. So something like the below.

from(bucket: “Bucket”)  
|\> range(start: v.timeRangeStart, stop: v.timeRangeStop)  
|\> filter(fn: (r) =\> r["\_measurement"] == “test”)  
|\> filter(fn: (r) =\> r["\_field"] == “Value1” or r["\_field"] == “value2”)  
|\>aggregateWindow(ever: if count(column:"\_value") \<= 10000 then 1m else 10s, fn mean())

---

<div class="post-metadata">

**Author:** ![scott](https://sea1.discourse-cdn.com/flex023/user_avatar/community.influxdata.com/scott/32/16492_2.png) [@scott](https://community.influxdata.com/u/scott)\
**Post date:** [April 5, 2022, 4:36pm UTC](https://community.influxdata.com/t/aggregate-window-with-dynamic-every-based-on-total-points/24368/2 "2022-04-05T16:36:23Z")

</div>

@Eto This is possible, but it won’t be very efficient since the query has to read the data twice (once to count the number of rows and another to aggregate the data). To make sure the query is as optimized as possible, structure the base dataset as a function. This allows pushdowns to continue beyond the data variable declaration.

```javascript
data = () => from(bucket: "Bucket")
    |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
    |> filter(fn: (r) => r["_measurement"] == "test")
    |> filter(fn: (r) => r["_field"] == "Value1" or r["_field"] == "value2")

count = (data() |> group() |> count() |> findColumn(fn: (key) => true, column: "_value"))[0]
every = if count <= 10000 then 1m else 10s

data()
    |> aggregateWindow(every: every, fn: mean)

```
