How to calculate a sum of the set of values using Aggregation

We have seen average calculation using Aggregation.
In this post, we will see how to calculate a sum of the set of values from a field. It works quite similar to avg function.

  • Aggregation can only be performed on numerical fields like Integers and Floats.
  • sum function calculates the sum of the set of numbers.
  • It can be performed with or without filters.
  • The distinct filter gives the sum of unique rows.
  • The where clause selects matching rows with specific field values. sum function then calculates the sum of the selected rows.

We will work with the same schema.

type AggObj {
    intFld: Int
    floatFld: Float
}

Let’s use the same 7 records from the previous post.

mutation {
  upsert(
    values: {
      AggObj: [
        { intFld: 1, floatFld: 1.1 }
        { intFld: 2, floatFld: 1.2 }
        { intFld: 3, floatFld: 1.3 }
        { intFld: 4, floatFld: 1.4 }
        { intFld: 4, floatFld: 1.4 }
        { intFld: 3, floatFld: 1.3 }
        { intFld: 1, floatFld: 1.1 }
      ]
    }
  ) {
    id
  }
}

Sample Query

Let’s find out the sum of all the floatFld values from the 7 records.

{
  aggregate {
    aggObj {
       floatFld {
        sum
      }
    }
  }
}
#result
{
  "data": {
    "aggregate": {
      "aggObj": {
        "floatFld": {
          "sum": 8.8
        }
      }
    }
  }
}

Now, we will use the distinct filter to find out the sum of unique values. The below query considers repeated values from floatFld as one value. So the count of records becomes 4 instead of 7.
The sum becomes (1.1+1.2+1.3+1.4) = 5

{
  aggregate {
    aggObj {
       floatFld {
        sum(distinct: true)
      }
    }
  }
}
#result
{
  "data": {
    "aggregate": {
      "aggObj": {
        "floatFld": {
          "sum": 5
        }
      }
    }
  }
}

Let’s find out the sum of the floatFld values where intFld values are 1.
Sum = 1.1 + 1.1 = 2.2

{
  aggregate {
    aggObj (where: "intFld=1") {
      floatFld {
        sum
      }
    }
  }
}
#Result
{
  "data": {
    "aggregate": {
      "aggObj": {
        "floatFld": {
          "sum": 2.2
        }
      }
    }
  }
}

Check the POSTMAN collection for the sum query in different programming languages! Click </> and choose the programming language of your choice.
Don’t forget to insert your own Authorization key and Hypi Domain under Headers to test the results!
Run in Postman