Skip to main content

Aggregates and grouping

An aggregate returns a value of the column's type. Grouped results go into a struct you define, through Project.

Sum, average, minimum, maximum​

SumOf, AvgOf, MinOf and MaxOf take a query and a column.

adults := db.Users.Where(ant.Gt(&Users.Age, 18))

total, err := ant.SumOf(ctx, adults, &Users.Age) // int
// SELECT SUM("users"."age") FROM "users" WHERE "users"."age" > $1

average, err := ant.AvgOf(ctx, adults, &Users.Age) // float64
// SELECT AVG("users"."age") FROM "users" WHERE "users"."age" > $1
// SQL Server: AVG(CAST("users"."age" AS FLOAT)), since its AVG keeps an integer's type

lowest, err := ant.MinOf(ctx, adults, &Users.Age) // int
// SELECT MIN("users"."age") FROM "users" WHERE "users"."age" > $1

last, err := ant.MaxOf(ctx, adults, &Users.Name) // string
// SELECT MAX("users"."name") FROM "users" WHERE "users"."age" > $1

Over no rows these calls return zero, not NULL. For a plain row count, see Count.

Group rows​

Define a struct for a result row, get its probe, and map columns and aggregates into it.

type AgeGroup struct {
Age int
Users int64
}

var AgeGroups = ant.Fields[AgeGroup]()

groups, err := ant.Project[AgeGroup](
db.Users.GroupBy(&Users.Age).Order(ant.Col(&Users.Age).Asc()),
ant.Into(&AgeGroups.Age, &Users.Age),
ant.IntoExpr(&AgeGroups.Users, ant.Count()),
).All(ctx)
// SELECT "users"."age" AS "age", COUNT(*) AS "users"
// FROM "users" GROUP BY "users"."age" ORDER BY "users"."age"

groups is a []AgeGroup. Both sides of each mapping are field pointers, so the compiler checks them.

Filter groups​

Where filters rows before grouping, and Having filters groups after.

groups, err := ant.Project[AgeGroup](
db.Users.
Where(ant.Gt(&Users.Age, 20)).
GroupBy(&Users.Age).
Having(ant.Count().Gt(1)).
Order(ant.Count().Desc()).
Limit(5),
ant.Into(&AgeGroups.Age, &Users.Age),
).All(ctx)
// SELECT "users"."age" AS "age" FROM "users"
// WHERE "users"."age" > $1
// GROUP BY "users"."age"
// HAVING COUNT(*) > $2
// ORDER BY COUNT(*) DESC
// LIMIT $3

Group by several columns or an expression​

ant.Then adds a column to the group, and GroupByExpr groups by an expression.

byAgeAndName := ant.Then(db.Users.GroupBy(&Users.Age), &Users.Name)
// ... GROUP BY "users"."age", "users"."name"

decade := ant.SQL[int]("? / 10", ant.Col(&Users.Age))

groups, err := ant.Project[AgeGroup](
db.Users.GroupByExpr(decade).Order(decade.Asc()),
ant.IntoExpr(&AgeGroups.Age, decade),
ant.IntoExpr(&AgeGroups.Users, ant.Count()),
).All(ctx)
// SELECT "users"."age" / 10 AS "age", COUNT(*) AS "users"
// FROM "users" GROUP BY "users"."age" / 10 ORDER BY "users"."age" / 10

Aggregate functions​

FunctionResult
ant.Count()int64, rows in the group
ant.CountOf(&Users.Bio)int64, rows where it isn't NULL
ant.CountDistinct(&Users.Age)int64, distinct values
ant.Sum(&Users.Age)the column's type
ant.Avg(&Users.Age)float64
ant.Min(&Users.Age), ant.Max(&Users.Age)the column's type

Each is an expression, so .Filter(...) narrows one aggregate without touching the rest of the query:

ant.IntoExpr(&AgeGroups.Users, ant.Count().Filter(ant.Eq(&Users.Name, "Ada")))
// COUNT(*) FILTER (WHERE "users"."name" = $1) AS "users"

FILTER is native on PostgreSQL and SQLite and written with CASE on the other databases. See databases.

Group across a join​

Group by a column of a joined model and count the rows of the other side.

type PostCount struct {
Author string
Posts int64
}

var PostCounts = ant.Fields[PostCount]()

counts, err := ant.Project[PostCount](
db.Posts.Join(&Posts.User).GroupBy(&Users.Name).Having(ant.Count().Gt(2)).Order(ant.Count().Desc()),
ant.Into(&PostCounts.Author, &Users.Name),
ant.IntoExpr(&PostCounts.Posts, ant.Count()),
).All(ctx)
// SELECT "users"."name" AS "author", COUNT(*) AS "posts"
// FROM "posts" JOIN "users" ON "posts"."user_id" = "users"."id"
// GROUP BY "users"."name"
// HAVING COUNT(*) > $1
// ORDER BY COUNT(*) DESC

An inner join drops authors with no posts. To count them as 0, start from the users and use a left join, counting a column of the posts:

counts, err := ant.Project[PostCount](
db.Users.LeftJoinMany(&Users.Posts).GroupBy(&Users.Name),
ant.Into(&PostCounts.Author, &Users.Name),
ant.IntoExpr(&PostCounts.Posts, ant.CountOf(&Posts.ID)),
).All(ctx)
// SELECT "users"."name" AS "author", COUNT("posts"."id") AS "posts"
// FROM "users" LEFT JOIN "posts" ON "users"."id" = "posts"."user_id"
// GROUP BY "users"."name"

To attach a count to whole models instead, see a computed field.