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.
Code
-- 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
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 tables does the SQL touch?
- `audit_events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.