Skip to content

Shares and running totals

“Now add each channel’s share of the total.” “Show a running total by day.” “And the change from last month.” These follow-ups come after a report already works, usually with a few minutes left. Do not rewrite the query. Wrap it in a CTE and add one window on top: the rows stay, and each row can see its group or its neighbours.

  1. Put the whole working query into WITH base AS (…). Change nothing inside, except that its ORDER BY is no longer needed.
  2. On top, write a new SELECT … FROM base with the window function.
  3. If you need to filter on the window (rn = 1), add one more step: WHERE cannot see a window.

Here the base is September net revenue per plan period, and the follow-up asks for the share of each period:

WITH by_period AS (
SELECT plan_period, COUNT(*) AS transactions, SUM(revenue_usd) AS net_usd
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2026-09-01'
AND start_time < TIMESTAMP '2026-10-01'
GROUP BY plan_period
)
SELECT plan_period, transactions, net_usd,
SUM(net_usd) OVER () AS total_usd,
ROUND(100.0 * net_usd / SUM(net_usd) OVER (), 1) AS share_pct
FROM by_period
ORDER BY net_usd DESC, plan_period;
plan_periodtransactionsnet_usdtotal_usdshare_pct
P1Y793449.355961.8157.9
P1M3042282.235961.8138.3
P1W80230.235961.813.9
  • SUM(net_usd) without OVER would collapse the result into one row. OVER () means “the sum over all rows, but keep the rows”: every row sees the total 5961.81.
  • The rounded shares add up to 100.1, not 100. That is rounding, not a bug; say so when you check.
  • Write 100.0, not 100. With integer columns, such as counts, 100 * a / b is integer division (see Conditional aggregation).

A window runs after WHERE and before ORDER BY and LIMIT. So LIMIT 2 keeps the shares 57.9 and 38.3: they are still shares of the full total. But a filter in the same SELECT, such as WHERE plan_period <> 'P1W', removes the row before the window. The total shrinks and the shares become 60.2 and 39.8. Decide which total the task means, and filter in the right step.

Without a window, the total is a scalar subquery: 100.0 * net_usd / (SELECT SUM(net_usd) FROM by_period). It is longer, but it gives the same numbers.

PARTITION BY gives each group its own total. Here is each product’s share of its merchant’s September revenue:

WITH per_product AS (
SELECT p.merchant_id, t.product_id, SUM(t.revenue_usd) AS net_usd
FROM transactions t
JOIN products p ON p.id = t.product_id
WHERE NOT t.is_test
AND t.start_time >= TIMESTAMP '2026-09-01'
AND t.start_time < TIMESTAMP '2026-10-01'
GROUP BY p.merchant_id, t.product_id
)
SELECT merchant_id, product_id, net_usd,
ROUND(100.0 * net_usd / SUM(net_usd) OVER (PARTITION BY merchant_id), 1) AS share_in_merchant_pct
FROM per_product
WHERE merchant_id IN ('mer_02', 'mer_06')
ORDER BY merchant_id, net_usd DESC;
merchant_idproduct_idnet_usdshare_in_merchant_pct
mer_02prd_02542.8445.7
mer_02prd_13377.7931.8
mer_02prd_16266.7522.5
mer_06prd_18313.8056.7
mer_06prd_06239.9043.3

The WHERE here filters by the partition key, so each merchant keeps all its products and the shares still add up to 100 per merchant.

Ask yourself “a share of what?” before you write PARTITION BY. If you partition by the same key as the GROUP BY before it, each group has one row and every share is 100%. For the report by channel this is worse: promo has 0 revenue, so it divides 0 by 0 and the query fails with division by zero. If a group total can be 0, divide by NULLIF(SUM(x) OVER (…), 0).

With ORDER BY inside OVER, SUM adds up the rows from the start of the group to the current row. Here are advances per merchant and month, with a running total that restarts for each merchant:

WITH monthly AS (
SELECT merchant_id, period_month, SUM(amount_usd) AS advanced_usd
FROM advances
WHERE merchant_id IN ('mer_01', 'mer_03')
GROUP BY merchant_id, period_month
)
SELECT merchant_id, period_month, advanced_usd,
SUM(advanced_usd) OVER (PARTITION BY merchant_id ORDER BY period_month) AS running_usd
FROM monthly
ORDER BY merchant_id, period_month;
merchant_idperiod_monthadvanced_usdrunning_usd
mer_012026-06-0189.1889.18
mer_012026-07-01145.09234.27
mer_012026-08-01125.45359.72
mer_032026-05-01214.13214.13
mer_032026-06-01220.06434.19
mer_032026-07-01169.50603.69
mer_032026-08-01175.44779.13

Check: the last running value of each merchant equals its plain SUM(amount_usd), 359.72 and 779.13.

Frames: what “up to the current row” means

Section titled “Frames: what “up to the current row” means”

The set of rows a window function sees for each row is its frame. With ORDER BY and no frame written, PostgreSQL uses RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Rows with an equal ORDER BY value are peers, and they enter the frame together. Without the monthly aggregation, mer_01 has two advances in each month:

SELECT advance_id, channel, period_month, amount_usd,
SUM(amount_usd) OVER (ORDER BY period_month) AS default_frame,
SUM(amount_usd) OVER (ORDER BY period_month, advance_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS rows_frame
FROM advances
WHERE merchant_id = 'mer_01'
ORDER BY period_month, advance_id;
advance_idchannelperiod_monthamount_usddefault_framerows_frame
adv_0001north_market2026-06-0168.3889.1868.38
adv_0004south_market2026-06-0120.8089.1889.18
adv_0002north_market2026-07-0148.75234.27137.93
adv_0005south_market2026-07-0196.34234.27234.27

These are the first four of six rows. The default frame gives both June rows 89.18, the total of the whole month. ROWS with a unique order counts row by row. Neither is wrong, but you must know which one you get. The simple rule: aggregate to one row per ORDER BY value first, as in the monthly query above. Then both frames give the same result.

A frame can also have a start that moves: ROWS BETWEEN 6 PRECEDING AND CURRENT ROW is the current row and the six before it. Here is daily net revenue of all merchants together, with a 7-day moving average:

WITH daily AS (
SELECT CAST(start_time AS DATE) AS day, SUM(revenue_usd) AS net_usd
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2026-09-01'
AND start_time < TIMESTAMP '2026-09-11'
GROUP BY 1
)
SELECT day, net_usd,
COUNT(*) OVER w AS days_in_frame,
ROUND(AVG(net_usd) OVER w, 2) AS avg_7d_usd
FROM daily
WINDOW w AS (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
ORDER BY day;
daynet_usddays_in_frameavg_7d_usd
2026-09-01201.821201.82
2026-09-02108.932155.38
2026-09-06293.876226.36
2026-09-07105.917209.15
2026-09-0857.897188.59

Five of ten rows are shown. The WINDOW clause names a window once, so two functions can share it.

  • The first six days average fewer than seven days. Ask whether the task wants that, or NULL until seven days exist (CASE WHEN COUNT(*) OVER w = 7 THEN … END).
  • ROWS counts rows, not days. If a day has no sales, it has no row, and “6 preceding” reaches eight days back. Here every day has sales. For one merchant it often does not: build a calendar first, see Calendars and active periods.

PostgreSQL can also measure the frame in days: RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW takes the rows whose day is at most six days before the current one. It needs exactly one ORDER BY column, here day. A missing day then cannot stretch the frame. But it does not replace the calendar: AVG divides by the rows that exist, not by seven, and a day without sales still has no row of its own. mer_01 has no sales from 5 to 8 September. Its 7-day average on 9 September:

framedays with sales onlyon a calendar
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW6.993.99
RANGE BETWEEN INTERVAL '6 days' PRECEDING AND CURRENT ROW9.323.99

Without the calendar, ROWS reaches back to 1 September, and RANGE averages only the three days with sales: 3, 4 and 9 September. On the calendar both give 3.99, and 8 September gets its own row, with 3.00. So the calendar with COALESCE(…, 0) is what puts the zero days into the average. RANGE with an interval only makes sure that a gap cannot widen the frame.

LAG(x) returns x from the previous row in the window order. LEAD(x) returns it from the next row. Here are mer_01’s South Market payouts, each with the previous one and the change:

SELECT period_month, amount_usd,
LAG(amount_usd) OVER (ORDER BY period_month) AS prev_usd,
amount_usd - LAG(amount_usd) OVER (ORDER BY period_month) AS change_usd
FROM channel_payouts
WHERE merchant_id = 'mer_01'
AND channel = 'south_market'
ORDER BY period_month;
period_monthamount_usdprev_usdchange_usd
2026-01-0129.71NULLNULL
2026-02-0141.5929.7111.88
2026-03-01103.6341.5962.04
2026-04-0135.65103.63-67.98

These are the first four of seven rows. The first month has no previous row, so it gets NULL, and the change is NULL too. LAG(x, 1, 0) would put 0 there instead, but then January shows a change of +29.71 that did not happen. Usually NULL is the honest answer. For several channels at once, add PARTITION BY channel.

LAG takes the previous row, not the previous day or month. mer_01 has no sales from 5 to 8 September:

WITH daily AS (
SELECT CAST(t.start_time AS DATE) AS day, SUM(t.revenue_usd) AS net_usd
FROM transactions t
JOIN products p ON p.id = t.product_id
WHERE p.merchant_id = 'mer_01'
AND NOT t.is_test
AND t.start_time >= TIMESTAMP '2026-09-01'
AND t.start_time < TIMESTAMP '2026-09-11'
GROUP BY 1
)
SELECT day, net_usd,
LAG(day) OVER (ORDER BY day) AS prev_day,
LAG(net_usd) OVER (ORDER BY day) AS prev_usd
FROM daily
ORDER BY day;
daynet_usdprev_dayprev_usd
2026-09-016.99NULLNULL
2026-09-020.002026-09-016.99
2026-09-0313.982026-09-020.00
2026-09-046.992026-09-0313.98
2026-09-096.992026-09-046.99

For 9 September the “previous day” is 4 September. If the task says “compared with the day before”, fill the calendar first. Without a window, a self-join on cur.month = prev.month + INTERVAL '1 month' also handles gaps: a missing month simply finds no match.

The base task is Q01, revenue by channel: transactions, gross and net per channel for September. You ask the usual questions, write it, and check it out loud. Then the interviewer says: “Nice. Finance also wants each channel’s share of the total net revenue.”

  1. Ask first: “In percent, rounded to one decimal? And the total is all channels together, including promo?”
  2. Plan out loud: “I’ll keep my query as a CTE and add one column on top: net divided by the total. The total comes from a window over all rows, so I keep one row per channel.”
  3. Wrap: the Q01 query becomes the first CTE, and the share is one new column in the outer SELECT.
  4. Check: “The shares add up to 100: 49.5 plus 38 plus 12.5.”

The first drill below is this step.

TalkSay it out loud

What if I add LIMIT 2 to the query with the shares?

Say your answer out loud first, then open it.

Show the answer

“The window is computed before ORDER BY and LIMIT, so the two rows keep their shares of the full total. Only a filter in WHERE of the same SELECT would change the total.”

SQLWrite a querycore

Share of each channel in September 2026 net revenue (revenue_usd), test purchases excluded, percent with 1 decimal.

Output columns: channel, net_usd, share_pctOrder: ORDER BY net_usd DESC, channel

Tables, columns and how they connect

transactions — one row = one paid (or trial) period of a subscription

  • channel — north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)
  • start_time — start of the period = time of purchase; "started in …" means this column
  • revenue_usd — revenue net of refunds: 0 if the transaction was refunded (net)
  • is_test — test purchase: exclude it from business numbers
channelstart_timerevenue_usdis_test
north_market2025-01-01 04:48:0379.99false
north_market2025-01-01 06:59:586.99false
north_market2025-01-01 02:08:336.99false

"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.

-- your query here
Show answer

Reference

WITH by_channel AS (
SELECT channel, SUM(revenue_usd) AS net_usd
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2026-09-01'
AND start_time < TIMESTAMP '2026-10-01'
GROUP BY channel
)
SELECT channel, net_usd,
ROUND(100.0 * net_usd / SUM(net_usd) OVER (), 1) AS share_pct
FROM by_channel
ORDER BY net_usd DESC, channel;

Expected output

channelnet_usdshare_pct
north_market2948.6749.5
south_market2265.6238.0
web747.5212.5
promo0.000.0
4 rows

The share of the total is SUM(…) OVER () over all rows of the result. PARTITION BY channel would give every channel 100%, because there is one row per channel, and it would divide promo by zero. Without a window, divide by a scalar subquery that sums net_usd over the same CTE.

SQLWrite a query

mer_04: net revenue per day for 14–20 September 2026 (test purchases excluded) and the running total. Only days with sales. Day as DATE.

Output columns: day, net_usd, running_usdOrder: ORDER BY day

Tables, columns and how they connect

transactions — one row = one paid (or trial) period of a subscription

  • product_id — → products.id
  • start_time — start of the period = time of purchase; "started in …" means this column
  • revenue_usd — revenue net of refunds: 0 if the transaction was refunded (net)
  • is_test — test purchase: exclude it from business numbers
product_idstart_timerevenue_usdis_test
prd_012025-01-05 05:52:570.00false
prd_012025-01-03 05:03:116.99false
prd_012025-01-10 11:02:396.99false

products — products (20 rows); a merchant can own several

  • id — key: prd_01 …
  • merchant_id — → merchants.id
idmerchant_id
prd_01mer_01
prd_02mer_02
prd_03mer_03

Joins: transactions.product_id = products.id

"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.

-- your query here
Show answer

Reference

WITH daily AS (
SELECT CAST(t.start_time AS DATE) AS day, SUM(t.revenue_usd) AS net_usd
FROM transactions t
JOIN products p ON p.id = t.product_id
WHERE p.merchant_id = 'mer_04'
AND NOT t.is_test
AND t.start_time >= TIMESTAMP '2026-09-14'
AND t.start_time < TIMESTAMP '2026-09-21'
GROUP BY 1
)
SELECT day, net_usd, SUM(net_usd) OVER (ORDER BY day) AS running_usd
FROM daily
ORDER BY day;

Expected output

daynet_usdrunning_usd
2026-09-1511.9611.96
2026-09-1616.9728.93
2026-09-172.9931.92
2026-09-206.9938.91
4 rows

A running total is SUM(…) OVER (ORDER BY day) on top of the daily totals. The task asks for days with sales only. mer_04 has no sales on 14, 18 and 19 September, so the result has four rows, and the running total jumps from 17 to 20 September. If the task said “every day”, you would start from a calendar built with generate_series, as in the drill on calendars. The hidden data has a sale late on 20 September, so the range must be half-open.

SQLWrite a query

Net revenue per month for January–September 2026 (test purchases excluded), the previous month's revenue and the change. For January 2026 the previous month is December 2025. Month as DATE.

Output columns: month, net_usd, prev_usd, change_usdOrder: ORDER BY month

Tables, columns and how they connect

transactions — one row = one paid (or trial) period of a subscription

  • start_time — start of the period = time of purchase; "started in …" means this column
  • revenue_usd — revenue net of refunds: 0 if the transaction was refunded (net)
  • is_test — test purchase: exclude it from business numbers
start_timerevenue_usdis_test
2025-01-01 02:08:336.99false
2025-01-01 04:48:0379.99false
2025-01-01 06:59:586.99false

"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.

-- your query here
Show answer

Reference

WITH monthly AS (
SELECT CAST(date_trunc('month', start_time) AS DATE) AS month, SUM(revenue_usd) AS net_usd
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2025-12-01'
AND start_time < TIMESTAMP '2026-10-01'
GROUP BY 1
),
with_prev AS (
SELECT month, net_usd, LAG(net_usd) OVER (ORDER BY month) AS prev_usd
FROM monthly
)
SELECT month, net_usd, prev_usd, net_usd - prev_usd AS change_usd
FROM with_prev
WHERE month >= DATE '2026-01-01'
ORDER BY month;

Expected output

monthnet_usdprev_usdchange_usd
2026-01-016273.124676.541596.58
2026-02-015271.406273.12-1001.72
2026-03-015651.265271.40379.86
2026-04-015390.165651.26-261.10
2026-05-015943.945390.16553.78
2026-06-016509.845943.94565.90
2026-07-016531.846509.8422.00
2026-08-017082.256531.84550.41
2026-09-015961.817082.25-1120.44
9 rows

The previous row is LAG(x) OVER (ORDER BY month). WHERE runs before the window, so a filter on 2026 in WHERE hides December 2025 from LAG, and January gets NULL. Compute the months from December 2025, take LAG, and only then keep 2026 in the outer query: January’s previous value is December’s 4676.54. Without a window, join monthly to itself on m.month = p.month + INTERVAL '1 month'.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.