Window Function Running Total Balance
Compute per-account running balances with a window function ordered by transaction time, including partition isolation.
Code
-- 按账户分区、按时间排序的累计余额
WITH ledger AS (
SELECT
account_id,
occurred_at,
amount_cents,
SUM(amount_cents) OVER (
PARTITION BY account_id
ORDER BY occurred_at, id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_balance
FROM transactions
WHERE status = 'settled'
)
SELECT
account_id,
occurred_at,
amount_cents,
running_balance,
LAG(running_balance, 1, 0) OVER (
PARTITION BY account_id ORDER BY occurred_at, id
) AS previous_balance
FROM ledger
WHERE running_balance < 0 -- 首次透支的时刻一目了然
ORDER BY account_id, occurred_at;
-- 配套索引:窗口的 PARTITION + ORDER 键
-- CREATE INDEX idx_tx_account_time
-- ON transactions (account_id, occurred_at, id);Inside the snippet
At its core this is a single SELECT statement against transactions and ledger.
In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause constraining which rows the statement operates on; SUM aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Points of care
- Window functions evaluate after
WHERE/GROUP BY, so filtering on their output in the same-levelWHEREwill not work — use an outer query or a CTE.
Putting it to use
Run the statement against the transactions table.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.
FAQ
- Which objects does the SQL touch?
- `transactions`, `ledger` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.