Window functions
A window function computes across a set of rows and keeps every row. Results come back through Project. A function such as ant.RowNumber() takes a window from Over, which sets the rows it sees and their order.
Number the rows
ant.OrderedBy builds a window from ordering terms. RowNumber().Over(window) gives each row its position in that order.
type Ranked struct {
Name string
Position int64
}
var Rankeds = ant.Fields[Ranked]()
byAge := ant.OrderedBy(ant.Col(&Users.Age).Asc(), ant.Col(&Users.Name).Asc())
rows, err := ant.Project[Ranked](
db.Users.OrderBy(&Users.Name),
ant.Into(&Rankeds.Name, &Users.Name),
ant.IntoExpr(&Rankeds.Position, ant.RowNumber().Over(byAge)),
).All(ctx)
// SELECT "users"."name" AS "name",
// ROW_NUMBER() OVER (ORDER BY "users"."age", "users"."name") AS "position"
// FROM "users" ORDER BY "users"."name"
The window's order is separate from the query's OrderBy. Here rows come back by name and are numbered by age.
Rank within a group
ant.PartitionBy restarts the numbering for each value of a column. This ranks users by name within each age:
perAge := ant.PartitionBy(&Users.Age).OrderBy(ant.Col(&Users.Name).Asc())
rows, err := ant.Project[Ranked](
db.Users.Where(),
ant.Into(&Rankeds.Name, &Users.Name),
ant.IntoExpr(&Rankeds.Position, ant.Rank().Over(perAge)),
).All(ctx)
// SELECT "users"."name" AS "name",
// RANK() OVER (PARTITION BY "users"."age" ORDER BY "users"."name") AS "position"
// FROM "users"
Build a leaderboard
With ages 30, 25, 25 and 20, a descending Rank gives 1, 2, 2, 4 and DenseRank gives 1, 2, 2, 3.
board := ant.OrderedBy(ant.Col(&Users.Age).Desc())
rows, err := ant.Project[Ranked](
db.Users.Where(),
ant.Into(&Rankeds.Name, &Users.Name),
ant.IntoExpr(&Rankeds.Position, ant.DenseRank().Over(board)),
).All(ctx)
// SELECT "users"."name" AS "name", DENSE_RANK() OVER (ORDER BY "users"."age" DESC) AS "position"
// FROM "users"
The functions
| Function | Gives |
|---|---|
ant.RowNumber() | 1, 2, 3, 4 |
ant.Rank() | 1, 2, 2, 4: gaps after ties |
ant.DenseRank() | 1, 2, 2, 3: no gaps |
ant.Lag(&Users.Age) | the previous row's value, NULL for the first |
ant.Lead(&Users.Age) | the next row's value, NULL for the last |
Running totals and neighbours
Any aggregate works as a window, which gives a running total. Lag and Lead read the row before or after.
type Running struct {
Total int
Previous sql.Null[int]
}
var Runnings = ant.Fields[Running]()
rows, err := ant.Project[Running](
db.Users.OrderBy(&Users.Name),
ant.IntoExpr(&Runnings.Total, ant.Sum(&Users.Age).Over(byAge)),
ant.IntoExpr(&Runnings.Previous, ant.Lag(&Users.Age).Over(byAge)),
).All(ctx)
// SELECT SUM("users"."age") OVER (ORDER BY "users"."age", "users"."name") AS "total",
// LAG("users"."age") OVER (ORDER BY "users"."age", "users"."name") AS "previous"
// FROM "users" ORDER BY "users"."name"
Over needs a function: ant.Col(&Users.Age).Over(w) is an error.
See it tested: tests/features/querying/window_test.go