Array Agg As A Window Function
array_agg works as a window function: collect rows seen so far into a running array, or gather the one-preceding-to-one-following neighbors per row.
Code
CREATE TEMP TABLE relay_legs (
leg int PRIMARY KEY,
runner text NOT NULL,
split_s int NOT NULL
);
INSERT INTO relay_legs VALUES
(1, 'ana', 312),
(2, 'bob', 298),
(3, 'cyd', 305),
(4, 'dan', 287),
(5, 'eve', 331);
-- array_agg 也能当 window function:把窗口里的行收进数组
SELECT
runner,
split_s,
-- 运行窗口:迄今所有已出场的跑者
array_agg(runner) OVER (ORDER BY split_s
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS runners_so_far,
-- 滑动窗口:前后一棒的邻居
array_agg(runner) OVER (ORDER BY split_s
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS neighbor_runners
FROM relay_legs
ORDER BY split_s;The mechanics of the run
What runs here is SELECT / INSERT / CREATE — relay_legs are the objects involved.
relay_legs this file itself materialises as a session-local temp table — no earlier step is required, and the session end tidies it up completely.
Clause by clause, expect: a window function (OVER (…)) deriving per-row values from the surrounding window while every row survives in the result; 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
Setup is internal: the session-local tables it queries (relay_legs) are made by the file, so a single complete run against a scratch database suffices.
Statements that matter
SELECT
runner,
split_s,
array_agg(runner) OVER (ORDER BY split_s
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS runners_so_far,
array_agg(runner) OVER (ORDER BY split_s
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS neighbor_runners
FROM relay_legs
ORDER BY split_s;
INSERT INTO relay_legs VALUES
(1, 'ana', 312),
(2, 'bob', 298),
(3, 'cyd', 305),
(4, 'dan', 287),
(5, 'eve', 331);
CREATE TEMP TABLE relay_legs (
leg int PRIMARY KEY,
runner text NOT NULL,
split_s int NOT NULL
);
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- The references are `relay_legs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.