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

snippet
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;