Skip to content

Running totals, LAG and LEAD

Use window frames for running sums and moving averages, and LAG or LEAD to compare a row with the one before or after.

Practise: 18 questions

When you need it

"Cumulative revenue by day", "7-day moving average", "balance after each transaction", "days since the previous order", "change from the last reading". Words that signal it: "running", "cumulative", "so far", "rolling", "previous", "next", "since last".

These are window functions with no GROUP BY. Each input row stays in the output, and the function looks at a neighbourhood of other rows.

The shape of the query

select ...,
       sum(x) over (partition by <group> order by <time>
                    rows between unbounded preceding and current row) as running,
       lag(x) over (partition by <group> order by <time>) as previous
from ...;

Step by step:

  1. Reduce to the grain you want to accumulate over (usually one row per day or per month). Windows run over rows, so duplicate days will give odd frames.
  2. PARTITION BY restarts the calculation per group, for example per account.
  3. ORDER BY inside OVER defines what "before" means.
  4. The frame (ROWS BETWEEN ...) defines how far back to look.
with daily as (
  select account_id, posted_at::date as day, sum(amount) as net
  from transactions
  where account_id = 1
  group by account_id, posted_at::date
)
select day, net,
       sum(net) over (order by day
                      rows between unbounded preceding and current row) as balance_change_to_date
from daily
order by day
limit 10;

A 7-row moving average and the gap since the previous row:

with daily as (
  select played_at::date as day, count(*) as plays
  from plays
  group by played_at::date
)
select day, plays,
       round(avg(plays) over (order by day rows between 6 preceding and current row), 1) as avg_7_rows,
       plays - lag(plays) over (order by day) as change_vs_prev_row,
       day - lag(day) over (order by day) as days_since_prev_row
from daily
order by day
limit 10;

Traps interviewers look for

Variations

In other warehouses

Practise running totals, lag and lead