From 303da9662f7cd566e52eedcf4f1a3a84924e62da Mon Sep 17 00:00:00 2001 From: Alexander Zobnin Date: Thu, 23 Sep 2021 12:45:51 +0300 Subject: [PATCH] Handle nulls correctly in average and sum aggregations --- pkg/timeseries/agg_functions.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/pkg/timeseries/agg_functions.go b/pkg/timeseries/agg_functions.go index 66c655e..8acb164 100644 --- a/pkg/timeseries/agg_functions.go +++ b/pkg/timeseries/agg_functions.go @@ -9,17 +9,33 @@ type AggregationFunc = func(points []TimePoint) *float64 func AggAvg(points []TimePoint) *float64 { sum := AggSum(points) - avg := *sum / float64(len(points)) + // Do not include nulls in the average + nonNullLength := 0 + for _, p := range points { + if p.Value != nil { + nonNullLength++ + } + } + if sum == nil || nonNullLength == 0 { + return nil + } + avg := *sum / float64(nonNullLength) return &avg } func AggSum(points []TimePoint) *float64 { var sum float64 = 0 + isNil := true for _, p := range points { if p.Value != nil { + isNil = false sum += *p.Value } } + // Skip empty frames + if isNil { + return nil + } return &sum }