Handle nulls correctly in average and sum aggregations

This commit is contained in:
Alexander Zobnin
2021-09-23 12:45:51 +03:00
parent 71f9ac3210
commit 303da9662f

View File

@@ -9,17 +9,33 @@ type AggregationFunc = func(points []TimePoint) *float64
func AggAvg(points []TimePoint) *float64 { func AggAvg(points []TimePoint) *float64 {
sum := AggSum(points) 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 return &avg
} }
func AggSum(points []TimePoint) *float64 { func AggSum(points []TimePoint) *float64 {
var sum float64 = 0 var sum float64 = 0
isNil := true
for _, p := range points { for _, p := range points {
if p.Value != nil { if p.Value != nil {
isNil = false
sum += *p.Value sum += *p.Value
} }
} }
// Skip empty frames
if isNil {
return nil
}
return &sum return &sum
} }