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.

SqlData Fetching

Code

snippet
-- 反向累计: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-level WHERE will 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

FAQ

Which relations are involved here?
`budget_days` — referenced directly, no join needed.