SQL

Running Totals (SUM OVER)

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Window aggregates with an implicit "rows up to here" frame give you running totals, cumulative counts, and ratchet-up metrics. No self-join needed.
SQL
Raw
-- Cumulative revenue by day
SELECT day,
       revenue,
       SUM(revenue) OVER (ORDER BY day) AS running_total
FROM   daily_revenue;

-- Running total per user
SELECT user_id, created_at, amount,
       SUM(amount) OVER (
         PARTITION BY user_id
         ORDER     BY created_at
       ) AS lifetime_value
FROM   orders;

-- Cumulative % of total
SELECT day, revenue,
       SUM(revenue) OVER (ORDER BY day)              AS cumulative,
       SUM(revenue) OVER ()                          AS grand_total,
       ROUND(100.0 * SUM(revenue) OVER (ORDER BY day)
                   / SUM(revenue) OVER (), 1)        AS cumulative_pct
FROM   daily_revenue
ORDER  BY day;
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.