Running Total With Window Functions

Compute a cumulative total per customer with a window frame, a pattern that replaces self-joins or application-side accumulation.

SqlData Integrity

Code

sqlsnippet
12 lines
SELECT
    customer_id,
    ordered_at,
    amount,
    SUM(amount) OVER (
        PARTITION BY customer_id
        ORDER BY ordered_at, order_id
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_total
FROM orders
WHERE status = 'paid'
ORDER BY customer_id, ordered_at;

How the snippet works

At its core this is a single SELECT statement against orders.

Mechanically, the statements are built from: a WHERE clause limiting the rows one statement is allowed to reach; SUM aggregation; a window function (OVER (…)) taking in surrounding rows without folding them into one; an ORDER BY that fixes the output order.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying it

The orders table is the working surface here.

Statements that matter

SELECT
customer_id,
ordered_at,
amount,
SUM(amount) OVER (
PARTITION BY customer_id
ORDER BY ordered_at, order_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM orders
WHERE status = 'paid'
ORDER BY customer_id, ordered_at;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`orders` — referenced directly, no join needed.