Xorthax now has totals, counts, and averages—but something still isn’t quite right. Every calculation uses all rows in the group.
What if he only wants to look at some of the rows?
That’s where window frames come in.
A window frame controls which rows are included in the calculation.
FUNCTION(...) OVER (
PARTITION BY column
ORDER BY column
ROWS BETWEEN ...
)
This lets you define a subset of rows relative to the current row.
| OrderDate | Amount |
|---|---|
| 2024-01-01 | 100 |
| 2024-01-05 | 150 |
| 2024-01-10 | 200 |
| 2024-01-15 | 50 |
Now apply a frame:
SELECT OrderDate, Amount,
SUM(Amount) OVER (
ORDER BY OrderDate
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
) AS Value
FROM Orders;
Result:
| OrderDate | Amount | Value |
|---|---|---|
| 2024-01-01 | 100 | 100 |
| 2024-01-05 | 150 | 250 |
| 2024-01-10 | 200 | 350 |
| 2024-01-15 | 50 | 250 |
Each row now only looks at itself and the row before it.
ORDER BY OrderDate creates a sequence.
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW defines the frame:
So each calculation uses a small window that moves row by row.
By changing the frame, you control exactly which rows are included.
For each order, calculate the sum of totalamount for the current order and the previous order based on orderdate.
| Column | Type |
|---|---|
| orderid | bigint |
| customerid | bigint |
| orderdate | timestamp without time zone |
| totalamount | double precision |
| status | text |
| Column |
|---|
| orderid |
| orderdate |
| totalamount |
| two_order_sum |
Now that you can control which rows are included, you can build more useful patterns.
Next, you’ll use this to calculate values that build over time.