Litestone guide / Advanced
Window functions
A window adds computed columns to each row from the rows around it: rankings, running totals, the previous row's value. Unlike aggregate(), no row is collapsed.
model Order {
id Int
accountId Int
amount Float
}
await db.order.createMany({ data: [
{ accountId: 1, amount: 10 },
{ accountId: 1, amount: 30 },
{ accountId: 1, amount: 20 },
] })
const rows = await db.order.findMany({
where: { accountId: 1 },
orderBy: { id: 'asc' },
window: {
rn: { rowNumber: true, orderBy: { id: 'asc' } },
running: { sum: 'amount', orderBy: { id: 'asc' } },
},
})
if (rows.length !== 3 || rows[2].rn !== 3 || rows[2].running !== 60) throw new Error('window columns are wrong')
Each key in window becomes a column on every row, alongside the row's own fields.
What else it can do
rank,denseRank,percentRank,cumeDistandntilenumber rows by anorderBypartitionByrestarts the computation per group, on one field or severallagandleadread the previous or next row, withoffsetanddefaultfirstValue,lastValueandnthValuepick a row from the windowsum,avg,min,maxandcountrun over the windowrows: [-6, 0]andrange: [-1, 1]set a rolling frame, withnullfor unboundedfilterrestricts which rows enter an aggregate window- A
limitapplies after the window is computed, so numbering is right on every page - A
selectkeeps a window column only if it names it
In depth: Window functions § Positional functions, § Partition BY, § Adjacent row functions, § Running aggregates, § Rolling window, § FILTER (WHERE)