Window Function Running Total

Compute running totals with SQL window functions for cumulative aggregation over ordered rows.

SqlData Integrity

Code

sqlsnippet
7 lines
SELECT
  date,
  revenue,
  SUM(revenue) OVER (ORDER BY date) AS running_total,
  SUM(revenue) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS weekly_sum
FROM daily_revenue
ORDER BY date;

How the snippet works

The statement is SELECT, touching daily_revenue.

What the statements actually assemble: SUM aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch for

  • The OVER (…) computation happens post-filter, so referencing it in WHERE fails — wrap it instead.

Applying it

The daily_revenue table is the working surface here.

Statements that matter

SELECT
date,
revenue,
SUM(revenue) OVER (ORDER BY date) AS running_total,
SUM(revenue) OVER (ORDER BY date ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS weekly_sum
FROM daily_revenue
ORDER BY date;

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`daily_revenue`.