Aggregate functions (SUM(), AVG(), COUNT(), MIN(), MAX()) can
be used as window functions by adding an OVER() clause with
ORDER BY. This produces a cumulative (running) calculation instead
of a single collapsed value.
SUM() OVER (ORDER BY ...).AVG() OVER (ORDER BY ...).RANGE BETWEEN UNBOUNDED PRECEDING AND
CURRENT ROW) that makes cumulative calculations work.PARTITION BY for per-group cumulative
metrics.01_ROW_NUMBER04_PARTITION_BY05_LAG_LEADSUM(column) OVER (ORDER BY sort_column) AS running_total
AVG(column) OVER (
PARTITION BY group_column
ORDER BY sort_column
) AS running_average_per_group
employes joined to departments
| Domain | Scenario |
|---|---|
| Banking | Running account balance after each transaction |
| Finance | Cumulative revenue-to-date, YTD tracking |
| Retail | Rolling 7-day average sales for demand forecasting |
| Logistics | Cumulative distance travelled per route |
SUM() OVER (ORDER BY x) always produces a running total –
it does, but only because of the default frame; explicitly writing
the frame clause makes intent clear to future readers.PARTITION BY when the running total should restart per
group (e.g., per account, per department) rather than run across the
entire table.ORDER BY present) with a full-table
total (ORDER BY absent) – omitting ORDER BY turns the “running”
calculation back into one grand total repeated on every row.ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW even though it
matches the default – explicit code survives refactors better than
code relying on implicit defaults.SUM(column) computed with a plain GROUP BY – they must match.Running totals computed this way are O(n) per partition after the
initial sort, versus the O(n²) cost of the classic self-join/correlated
subquery pattern (SUM(...) WHERE b.id <= a.id). This is one of the
clearest performance wins window functions offer over pre-window-function
SQL patterns.
emp_id using SUM() OVER().emp_id using AVG() OVER().PARTITION BY.Intermediate
25–30 minutes
ORDER BY is what turns an aggregate
window function into a “running” calculation.08_Subqueries_Advanced (or the next module in your handbook sequence)
← Previous: 06_FIRST_LAST_NTILE
↑ Module README
→ Next: This is the final lesson in this module — see the Module README for the full roadmap.