String Agg Cumulative Window

Build running event trails with string_agg as a window aggregate: ROWS frames accumulate from the partition start or a trailing window of recent steps.

SqlData Integrity

Code

snippet
-- string_agg 也能当窗口聚合:ROWS 帧里逐行累积拼接
SELECT
    user_id,
    occurred_at,
    action,
    -- 从会话第一行到当前行的动作轨迹
    string_agg(action, ' -> ') OVER timeline AS trail,
    -- 只看最近 3 步的滑动窗口
    string_agg(action, ' -> ') OVER recent AS recent_trail
FROM audit_events
WHERE user_id = 42
WINDOW
    timeline AS (ORDER BY occurred_at
                 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW),
    recent AS (ORDER BY occurred_at
               ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
ORDER BY occurred_at;

How the snippet works

At its core this is a single SELECT statement against audit_events.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.

Applying it

The audit_events table is the working surface here.

Interactive Tools for This Topic

FAQ

Which tables does the SQL touch?
`audit_events` — referenced directly, no join needed.