Window Sum Remaining Budget Frame
SUM over ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING walks forward to the partition end, producing remaining budget beside the usual running total.
Code
-- 反向累计:ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
-- 从当前行一路加到分区末尾,得到"剩余量",不需要把数据反过来排
CREATE TABLE budget_days (
day date PRIMARY KEY,
planned_cost integer NOT NULL
);
SELECT
day,
planned_cost,
SUM(planned_cost) OVER (ORDER BY day) AS spent_so_far,
SUM(planned_cost) OVER (
ORDER BY day
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
) AS remaining
FROM budget_days
ORDER BY day;
-- 第一行的 remaining 就是总量;最后一行 remaining = 最后一行自己的支出How it works
Several statements share this file — SELECT / CREATE, with budget_days among the objects involved.
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
Run it in the budget_days database context.
Statements that matter
SELECT
day,
planned_cost,
SUM(planned_cost) OVER (ORDER BY day) AS spent_so_far,
SUM(planned_cost) OVER (
ORDER BY day
ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING
) AS remaining
FROM budget_days
ORDER BY day;
CREATE TABLE budget_days (
day date PRIMARY KEY,
planned_cost integer NOT NULL
);
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.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which relations are involved here?
- `budget_days` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.