Litestone guide / Querying
Aggregates and group-by
aggregate computes counts, sums and averages over the matching rows and returns one object. groupBy does the same per group and returns one row for each.
model Order {
id Int
accountId Int
status String ("pending")
amount Float
}
await db.order.createMany({ data: [
{ accountId: 1, status: 'paid', amount: 10 },
{ accountId: 1, status: 'paid', amount: 30 },
{ accountId: 2, status: 'pending', amount: 5 },
] })
const total = await db.order.aggregate({ where: { status: 'paid' }, _count: true, _sum: { amount: true }, _avg: { amount: true } })
if (total._count !== 2 || total._sum.amount !== 40 || total._avg.amount !== 20) throw new Error('aggregate: ' + JSON.stringify(total))
const byStatus = await db.order.groupBy({ by: ['status'], _count: true, _sum: { amount: true }, orderBy: { _count: 'desc' } })
if (byStatus[0].status !== 'paid' || byStatus[0]._count !== 2) throw new Error('groupBy: ' + JSON.stringify(byStatus))
const big = await db.order.groupBy({ by: ['accountId'], _sum: { amount: true }, having: { _sum: { amount: { gt: 20 } } } })
if (big.length !== 1 || big[0].accountId !== 1) throw new Error('having: ' + JSON.stringify(big))
What else it can do
_minand_maxtake fields, such as_max: { createdAt: true }_count: { distinct: 'accountId' }counts distinct values_stringAggjoins values into one string- A named aggregate takes a
filter, so one pass answers several questions havingfilters groups after they are formedbytakes several fields, andorderBysorts by a group field or an aggregategroupBycan bucket aDateTimeby day, week or month, with gaps filled- Over no rows,
_countis0and every other value isnull - A protected column cannot be aggregated by a caller who cannot read it
In depth: Aggregation § aggregate(), § Named aggregates + FILTER, § groupBy(), § HAVING