Xorthax now understands how to group data, order it, and control which rows are included. Now he wants to answer a very common question:
“How much has happened so far?”
That’s a running total.
A running total adds values step-by-step as you move through ordered rows.
SUM(column) OVER (
PARTITION BY column
ORDER BY column
)
The logic is:
PARTITION BY defines the groupORDER BY defines the sequence| OrderDate | CustomerID | Amount |
|---|---|---|
| 2024-01-01 | A | 100 |
| 2024-01-05 | A | 150 |
| 2024-01-10 | A | 200 |
SELECT OrderDate, CustomerID, Amount,
SUM(Amount) OVER (
PARTITION BY CustomerID
ORDER BY OrderDate
) AS RunningTotal
FROM Orders;
Result:
| OrderDate | CustomerID | Amount | RunningTotal |
|---|---|---|---|
| 2024-01-01 | A | 100 | 100 |
| 2024-01-05 | A | 150 | 250 |
| 2024-01-10 | A | 200 | 450 |
Each row shows the total up to that point in time.
ORDER BY OrderDate puts the rows in sequence from earliest to latest.
From the previous lesson, you learned that a window frame controls which rows are included in the calculation.
In this case, we didn’t write a frame—but SQL still uses one by default.
It includes:
That’s why the total keeps growing as you move down the table.
Later, you’ll learn how to control this more precisely using options like UNBOUNDED PRECEDING.
For each order, calculate a running total of totalamount for each customer, ordered by orderdate.
| Column | Type |
|---|---|
| orderid | bigint |
| customerid | bigint |
| orderdate | timestamp without time zone |
| totalamount | double precision |
| status | text |
| Column |
|---|
| customerid |
| orderid |
| orderdate |
| totalamount |
| running_total |
Running totals use all previous rows.
Next, you’ll learn how to limit the calculation to a smaller window that moves with each row.