Window Sums Restart Each Month
Restart running totals per month with PARTITION BY date_trunc expression keys, so each bucket starts its own cumulative sum beside the all-time total.
Code
-- window 函数的 PARTITION BY 接受任意表达式:用 date_trunc('month', …) 当分区键,
-- 运行总额在每个自然月 restart 清零,总累计照常进行
CREATE TEMP TABLE expenses (
id int PRIMARY KEY,
account_id int NOT NULL,
spent_at date NOT NULL,
cents int NOT NULL
);
INSERT INTO expenses VALUES
(1, 10, DATE '2026-10-05', 1200),
(2, 10, DATE '2026-10-20', 800),
(3, 10, DATE '2026-11-02', 300), -- 11 月:月累计从这里重新起算
(4, 20, DATE '2026-10-12', 500);
SELECT
account_id, spent_at, cents,
SUM(cents) OVER (
PARTITION BY account_id
ORDER BY spent_at
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS all_time_running,
SUM(cents) OVER (
PARTITION BY account_id, date_trunc('month', spent_at)
ORDER BY spent_at
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS month_running
FROM expenses
ORDER BY account_id, spent_at;
-- 账户 10 的 11 月行:month_running = 300,all_time_running = 2300
DROP TABLE expenses;How the snippet works
What runs here is SELECT / INSERT / CREATE — expenses are the objects involved.
expenses is a session-local temp table the file declares itself: no setup beforehand, and the table disappears when the session ends.
Mechanically, the statements are built from: SUM aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
What to watch for
- 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.
Applying it
Nothing outside the file is needed: the session-local tables it touches (expenses) are created by the file itself — point it at a scratch database and run the whole thing.
Statements that matter
INSERT INTO expenses VALUES
(1, 10, DATE '2026-10-05', 1200),
(2, 10, DATE '2026-10-20', 800),
(3, 10, DATE '2026-11-02', 300), -- 11 月:月累计从这里重新起算
(4, 20, DATE '2026-10-12', 500);
CREATE TEMP TABLE expenses (
id int PRIMARY KEY,
account_id int NOT NULL,
spent_at date NOT NULL,
cents int NOT NULL
);
DROP TABLE expenses;
Interactive Tools for This Topic
FAQ
- Which tables or CTEs does it reference?
- The references are `expenses`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.