Sub topic 6
Running totals and per-group aggregates
Assume you know SELECT, GROUP BY, aggregate functions such as SUM and AVG, and common table expressions. A window aggregate is an aggregate function that calculates across related rows while keeping one output row for each input row.
Why use a window aggregate?
GROUP BY combines rows into one row per group. A window aggregate calculates a group value and repeats it on every row in that group.
Suppose sales contains id, region, salesperson, and amount:
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;SUM(amount) OVER (...) is a window expression. The PARTITION BY region clause creates one window for each region. Each sale remains visible, alongside the total for its region and its percentage of that total.
| Query style | Result |
|---|---|
| `GROUP BY region` | One row per region |
| `SUM(amount) OVER (PARTITION BY region)` | One row per sale, with its region total |
A window does not mean a physical table or temporary object. It means the set of rows that a window function can inspect for the current row.
Running totals with an ordered window
Add an ORDER BY inside OVER when the result depends on row order. A running total includes the current row and all earlier rows in that order.
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
FROM sales;UNBOUNDED PRECEDING means the first row in the region. CURRENT ROW means the row currently being calculated. The id tie-breaker makes the order deterministic when two sales have the same date.
An explicit ROWS frame is useful because it states exactly which physical rows belong to the calculation. Without a frame, database defaults can treat tied ordering values differently.
Moving averages
The same structure can calculate a moving average. This example averages the current sale and the two preceding sales within each region:
SELECT
region,
sale_date,
amount,
AVG(amount) OVER (
PARTITION BY region
ORDER BY sale_date, id
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS moving_avg_3
FROM sales;At the beginning of a region, fewer than three rows exist, so the average uses the available rows. AVG ignores NULL amounts, while SUM also ignores them. If every value in a frame is NULL, both functions return NULL.
Exercise
Exercise
How would you calculate each employee's salary and the average salary for that employee's department on the same row?
Show answer
Use AVG(salary) OVER (PARTITION BY department), for example: SELECT employeename, department, salary, AVG(salary) OVER (PARTITION BY department) AS departmentavg FROM employees;