Search code examples
grafanainfluxdb

Can I calculate a moving sum on a field in InfluxDB?


I'm trying to understand if it's possible to calculate a 1 month sum of revenue data in one of my measurements. For each day, I would like the sum of the previous 30 days.

Is this possible in InfluxDB or through Grafana's query interface?


Solution

  • A moving average is a moving sum, divided by the number of samples. So if you want a moving sum of the past 30 values:

    select 30*moving_average(field_name, 30) from measurement
    

    Edited to add:

    As Peter Halicky points out in the comments, this is is not the past 30 days. It's the past 30 data points.

    If you will always have data for every single day, it's not an issue.

    If you're missing a day's data, you'll still get a 30-sample average, but it'll stretch over 31 days instead of 30.

    If you don't actually care about the calendar, but want to know the past 30 days of activity, this is not a problem.

    If it is a problem, there are a few work-arounds. One that's probably trickier than it sounds: ensure that there is always an entry for each day.

    A more robust way is to have the reporting app do this in two steps. Something like this (haven't worked out all the details, but you get the idea):

    1. find the number of data points in the past 30 days, using a query like select count(field_name) from measurement where time > now() - 30d.
    2. Use this number (call it n) to form the query: select n*moving_average(field_name, n) from measurement where time > now - 30d.