Sub topic 6
Running totals and per-group aggregates
This chapter assumes you can write GROUP BY queries with SUM, COUNT and AVG. It also assumes you can read an OVER (PARTITION BY ... ORDER BY ...) clause. Any aggregate function can become a window function by adding OVER. This chapter covers the two common uses: a per-group value repeated on every row, and a running value that grows as you move through the rows.
Setup
The examples use this table. The statements run on PostgreSQL and SQLite 3.25+. Other databases may need small changes to the DATE type.
CREATE TABLE sales (
id INTEGER PRIMARY KEY,
region VARCHAR(20),
salesperson VARCHAR(20),
sale_date DATE,
amount NUMERIC(10,2)
);
INSERT INTO sales (id, region, salesperson, sale_date, amount) VALUES
(1, 'East', 'Ana', '2026-01-05', 100),
(2, 'East', 'Ben', '2026-01-05', 50),
(3, 'East', 'Ana', '2026-01-12', 150),
(4, 'West', 'Cy', '2026-01-03', 200),
(5, 'West', 'Dee', '2026-01-10', 100),
(6, 'West', 'Cy', '2026-01-10', 300);Aggregates with OVER keep every row
SUM, AVG, COUNT, MIN and MAX all accept an OVER clause. With GROUP BY, each group collapses to one row. With OVER, every input row stays in the output, and the aggregate is computed over that row's window.
SELECT
id,
region,
salesperson,
amount,
SUM(amount) OVER (PARTITION BY region) AS region_total,
amount * 100.0 / SUM(amount) OVER (PARTITION BY region) AS pct_of_region
FROM sales;| id | region | salesperson | amount | region_total | pct_of_region |
|---|---|---|---|---|---|
| 1 | East | Ana | 100 | 300 | 33.33 |
| 2 | East | Ben | 50 | 300 | 16.67 |
| 3 | East | Ana | 150 | 300 | 50.00 |
| 4 | West | Cy | 200 | 600 | 33.33 |
| 5 | West | Dee | 100 | 600 | 16.67 |
| 6 | West | Cy | 300 | 600 | 50.00 |
Each sale keeps its own row and also shows its region's total. A GROUP BY query could only produce this by joining the grouped result back to the table.
The multiplier 100.0 is deliberate. If both operands were integers, some databases (SQL Server and PostgreSQL with integer columns, for example) would use integer division and return 0 or 33 instead of 33.33.
Windows without PARTITION BY
An empty OVER () makes the whole result set one partition. This gives a grand total on every row, or a comparison with the overall average:
SELECT
id,
region,
amount,
AVG(amount) OVER (PARTITION BY region) AS region_avg,
amount - AVG(amount) OVER (PARTITION BY region) AS diff_from_region_avg,
SUM(amount) OVER () AS grand_total
FROM sales;For East the average is 100, so the differences are 0, -50 and 50. For West the average is 200, so they are 0, -100 and 100. The grand total is 900 on every row. Different functions in one SELECT can use different windows.
Adding ORDER BY turns the total into a running total
Without ORDER BY, every row in a partition sees the same window: the whole partition. With ORDER BY, each row's window changes. It now covers the rows from the start of the partition up to the current row, and that is what produces a running total.
The diagram below shows how one partition produces a running total.
Here is the running total together with a three-row moving average:
SELECT
region,
sale_date,
amount,
SUM(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total,
AVG(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving_avg_3
FROM sales;| region | sale_date | amount | running_total | moving_avg_3 |
|---|---|---|---|---|
| East | 2026-01-05 | 100 | 100 | 100 |
| East | 2026-01-05 | 50 | 150 | 75 |
| East | 2026-01-12 | 150 | 300 | 100 |
| West | 2026-01-03 | 200 | 200 | 200 |
| West | 2026-01-10 | 100 | 300 | 150 |
| West | 2026-01-10 | 300 | 600 | 200 |
Three details to note:
- The running total restarts at each region because
PARTITION BYisolates the regions. - The moving average of the first rows uses fewer than three values. The frame stops at the partition's edge, so row 2 of East averages 100 and 50 only.
- The final running total of each partition equals that partition's
SUM. This is a good sanity check.
The ROWS BETWEEN ... part is the frame clause. A later chapter covers it fully. For now, read it as "which rows, counted by position relative to the current row, feed the aggregate".
The ties trap in running totals
Writing a running total with only ORDER BY sale_date looks fine, but it can give surprising numbers:
SELECT
region,
sale_date,
amount,
SUM(amount) OVER (PARTITION BY region ORDER BY sale_date) AS running_total
FROM sales;| region | sale_date | amount | running_total |
|---|---|---|---|
| East | 2026-01-05 | 100 | 150 |
| East | 2026-01-05 | 50 | 150 |
| East | 2026-01-12 | 150 | 300 |
| West | 2026-01-03 | 200 | 200 |
| West | 2026-01-10 | 100 | 600 |
| West | 2026-01-10 | 300 | 600 |
When you give ORDER BY and no frame, the standard default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. RANGE treats rows with equal sort values as peers, and a row's frame includes all of its peers. Both East rows dated 2026-01-05 therefore see 150, and no row shows the intermediate 100.
This may be what you want, for example "total through the end of each day". Usually it is not. For a row-by-row running total, do two things:
- Make the order unique by adding a tiebreaker such as
idto the windowORDER BY. - Write the frame explicitly with
ROWS, as in the earlier example.
Both steps matter. The unique order makes the sequence deterministic. The ROWS frame stops peers from being merged into one value. The default frame has other consequences too, and a later chapter returns to it.
Choosing the window for each need
| You want | Window definition |
|---|---|
| A per-group value on every row | `OVER (PARTITION BY g)` |
| A grand total on every row | `OVER ()` |
| A running total per group | `OVER (PARTITION BY g ORDER BY k, id ROWS UNBOUNDED PRECEDING)` |
| A moving average of the last N rows | `ROWS BETWEEN N-1 PRECEDING AND CURRENT ROW` |
| A running total across all rows | `OVER (ORDER BY k, id ROWS UNBOUNDED PRECEDING)` |
ROWS UNBOUNDED PRECEDING is shorthand for ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
NULLs and empty frames
Aggregate window functions follow the usual aggregate rules:
SUM,AVG,MINandMAXignoreNULLinputs.COUNT(amount)counts only non-NULLvalues, whileCOUNT(*)counts rows.- If every value in a frame is
NULL, or the frame holds no rows,SUM,AVG,MINandMAXreturnNULL.COUNTreturns 0.
Wrap a result in COALESCE(..., 0) only if a zero is the correct meaning for your report. A moving average over a frame that ignores NULL values divides by the number of non-NULL values, not by the frame size.
Combining windows with GROUP BY
Window functions run after GROUP BY and HAVING. So in a grouped query, a window function sees the grouped rows, and its argument must be something available after grouping, usually an aggregate:
SELECT
region,
SUM(amount) AS region_total,
SUM(SUM(amount)) OVER () AS grand_total,
SUM(amount) * 100.0 / SUM(SUM(amount)) OVER () AS pct_of_total
FROM sales
GROUP BY region;| region | region_total | grand_total | pct_of_total |
|---|---|---|---|
| East | 300 | 900 | 33.33 |
| West | 600 | 900 | 66.67 |
The inner SUM(amount) is the ordinary aggregate for each region. The outer SUM(...) OVER () adds up those two grouped rows. Writing SUM(amount) OVER () here would fail in most databases, because amount is neither grouped nor aggregated at that point.
Common errors
- Missing
OVER.SELECT id, SUM(amount) FROM salesis an aggregate query and fails becauseidis ungrouped. AddOVER (...)to keep the rows. - Wrong partition. Omitting
PARTITION BYgives a running total across all regions, not one per region. - No tiebreaker. If the window
ORDER BYhas ties and the frame isROWS, the order among tied rows is arbitrary, so results can differ between runs. Add a unique column. - Filtering in
WHERE.WHERE running_total > 200is not allowed. Compute it in a CTE or subquery and filter outside, as an earlier chapter showed. - Integer arithmetic. Percentages and averages over integer columns may truncate. Multiply by
100.0or cast first.
Exercise
Using the sales table, write a query that returns id, region, amount, and a running total of amount per region ordered by saledate, with ties broken by id. Then add a column showing each sale's share of its region's total. What are the runningtotal values for the West region?
Show answer
SELECT id, region, amount, SUM(amount) OVER (PARTITION BY region ORDER BY saledate, id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS runningtotal, amount * 100.0 / SUM(amount) OVER (PARTITION BY region) AS pctofregion FROM sales; The second window has no ORDER BY, so it covers the whole partition. The West running totals are 200, 300 and 600, for ids 4, 5 and 6. The shares are 33.33, 16.67 and 50.00.
Exercise
Why does SUM(amount) OVER (PARTITION BY region ORDER BY sale_date) return 150 for both East rows dated 2026-01-05, and how do you get 100 and then 150?
Show answer
With ORDER BY and no frame, the default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, and RANGE includes all peer rows that tie on saledate. Both rows are peers, so both see 100 + 50 = 150. To get 100 then 150, order by saledate, id and use ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.