First Value Window Addressing
Point at the first row of each partition with first_value, and keep the current row intact — unlike aggregate functions that collapse rows.
Code
-- 每个分区的首行值随行携带:行数不变,行不折叠
WITH page_views AS (
SELECT * FROM (VALUES
('signup', 1, 10),
('signup', 2, 7),
('signup', 3, 12),
('checkout', 1, 45),
('checkout', 2, 31)
) AS t(page, step, seconds)
)
SELECT
page,
step,
seconds,
-- 分区内按 step 排序后的第一个值:入口页耗时
FIRST_VALUE(seconds) OVER (
PARTITION BY page
ORDER BY step
) AS entry_seconds,
-- 与首值的差:后续步骤相对入口的增量
seconds - FIRST_VALUE(seconds) OVER (
PARTITION BY page
ORDER BY step
) AS delta_from_entry
FROM page_views
ORDER BY page, step;How it works
At its core this is a single SELECT statement against page_views.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Watch out 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.
Using it
Run the statement against the page_views table.
Interactive Tools for This Topic
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.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.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 this file reference?
- `page_views`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.