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.

SqlData Fetching

Code

snippet
-- 每个分区的首行值随行携带:行数不变,行不折叠
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-level WHERE will not work — use an outer query or a CTE.

Using it

Run the statement against the page_views table.

Interactive Tools for This Topic

FAQ

Which tables does this file reference?
`page_views`.