← 中文资源

简体中文版本

窗口帧 RANGE 对 NULL 并列行的分组行为

对比排序键含 NULL 时的 ROWS 与 RANGE 窗口帧:ROWS 逐行递进,而 RANGE 将所有 NULL 行视作同一组并列行,且数值偏移窗只匹配同为 NULL 的同伴行。

阅读英文原文

实现说明

实际执行的是 SELECT / INSERT / CREATE——player_scores 是涉及的对象。 player_scores 是文件自己造的会话级临时表——库里不会有残留,会话终结即被清理。 逐子句看,这些语句使用了:用 COUNT 做聚合;窗口函数(OVER (…))跨行取值求值,每行仍保持独立;ORDER BY 固定了输出顺序;强制行身份的 PRIMARY KEY。

使用要点

  • 窗口函数在 WHERE 与 GROUP BY 之后求值——同级 WHERE 看不见它的输出。

常见问题

这里涉及哪些关系(表/CTE)?

引用的是 player_scores。

核心语句

INSERT INTO player_scores VALUES
    ('ada', 10),
    ('ben', 20),
    ('cyd', NULL),
    ('dan', NULL);
CREATE TEMP TABLE player_scores (
    player text PRIMARY KEY,
    points integer
);

代码示例

CREATE TEMP TABLE player_scores (
    player text PRIMARY KEY,
    points integer
);

INSERT INTO player_scores VALUES
    ('ada', 10),
    ('ben', 20),
    ('cyd', NULL),
    ('dan', NULL);

SELECT
    player,
    points,
    -- ROWS steps one row at a time even across equal or NULL sort keys
    COUNT(*) OVER (
        ORDER BY points ASC NULLS LAST
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS rows_running_count,
    -- RANGE groups all NULL rows as peers, so cyd and dan jump together
    COUNT(*) OVER (
        ORDER BY points ASC NULLS LAST
        RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS range_running_count,
    -- Numeric RANGE offsets match NULL only against other NULL peers
    COUNT(*) OVER (
        ORDER BY points ASC NULLS LAST
        RANGE BETWEEN 5 PRECEDING AND 5 FOLLOWING
    ) AS range_window_peers
FROM player_scores
ORDER BY points ASC NULLS LAST, player;