MS SQL Server: Aggregation queries¶
Table of contents
Aggregate fields¶
You can fetch aggregations on columns along with nodes using an aggregation query.
The name of the aggregate field is of the form <field-name> + _aggregate
.
Common aggregation functions are count
, sum
, avg
, max
, min
, etc. You can see the complete
specification of the aggregate field in the API reference.
Note
For more advanced use cases, you can use views.
Fetch aggregated data of an object¶
Example: Fetch a list of articles with aggregated data of their rating:
query {
articles_aggregate {
aggregate {
count
sum {
rating
}
avg {
rating
}
max {
rating
}
}
}
}
query {
articles_aggregate {
aggregate {
count
sum {
rating
}
avg {
rating
}
max {
rating
}
}
}
}
{
"data": {
"articles_aggregate": {
"aggregate": {
"count": 10,
"sum": {
"rating": 26
},
"avg": {
"rating": 2.6
},
"max": {
"rating": 4
}
}
}
}
}
Fetch aggregated data on nested objects¶
The following is an example of a nested object query with aggregations on the array relationship between an author and articles.
Example: Fetch author with id “1” and a nested list of articles with aggregated data of their rating:
query {
authors (where: {id: {_eq: 1}}) {
id
name
articles_aggregate {
aggregate {
count
avg {
rating
}
max {
rating
}
}
}
}
}
query {
authors (where: {id: {_eq: 1}}) {
id
name
articles_aggregate {
aggregate {
count
avg {
rating
}
max {
rating
}
}
}
}
}
{
"data": {
"authors": [
{
"id": 1,
"name": "Justin",
"articles_aggregate": {
"aggregate": {
"count": 2,
"avg": {
"rating": 2.5
},
"max": {
"rating": 4
}
},
}
}
]
}
}