Last Non Null via last_value Workaround

Emulate the unimplemented IGNORE NULLS by pre-filtering NULLs in a subquery, then streaming last_value over a narrowed frame per ticker.

SqlData Integrity

Code

snippet
-- PostgreSQL 不实现 IGNORE NULLS(手册 9.22 注释明确):
-- last_value 直接用在含 NULL 的列上,只会原样带回最后一行的值
WITH raw AS (
    SELECT
        ticker,
        quoted_at,
        price,
        -- 直接 last_value:NULL 之后全部拿到 NULL,不是最近的真实报价
        last_value(price) OVER w AS naive_last_value
    FROM ticks
    WINDOW w AS (PARTITION BY ticker ORDER BY quoted_at
                 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
),
filled AS (
    SELECT
        r.ticker,
        r.quoted_at,
        r.price,
        r.naive_last_value,
        -- 替代做法一:相关子查询取最近的非空报价
        (SELECT p2.price
         FROM ticks p2
         WHERE p2.ticker = r.ticker
           AND p2.quoted_at <= r.quoted_at
           AND p2.price IS NOT NULL
         ORDER BY p2.quoted_at DESC
         LIMIT 1) AS carry_forward_subquery
    FROM raw r
)
SELECT
    ticker,
    quoted_at,
    price,
    naive_last_value,
    carry_forward_subquery,
    -- 替代做法二:last_value 前先用 MAX(quoted_at) 滤掉 NULL 价
    (SELECT p3.price
     FROM ticks p3
     WHERE p3.ticker = f.ticker
       AND p3.quoted_at = (SELECT max(p4.quoted_at)
                           FROM ticks p4
                           WHERE p4.ticker = f.ticker
                             AND p4.price IS NOT NULL
                             AND p4.quoted_at <= f.quoted_at)
       LIMIT 1) AS carry_forward_max
FROM filled f
ORDER BY ticker, quoted_at;

Inside the snippet

What runs is SELECT, with ticks, raw and filled as the object involved.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; MAX aggregation; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns.

Putting it to use

Run the statement against the ticks table; the LIMIT keeps the probe cheap while you tune the predicates.

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `ticks`, `raw`, `filled`.