如何在 PostgreSQL 中获取分区 (window) 的大小?

How to get the size of a partition (window) in PostgreSQL?

当我使用window时,如何获取当前分区的大小(行数)?

例如,假设我有一个 table 保存博客中 post 的评论。我想知道每个 post 的第一条评论、第二条评论、最后一条评论和评论数量是什么(没有另一个子查询,我按 post 分组并执行 COUNT(*) ).

查询应如下所示:

SELECT DISTINCT
    post_id.
    first_value(comment_text) OVER wnd AS first_comment,
    nth_value(comment_text, 2) OVER wnd AS second_comment,
    last_value(comment_text) OVER wnd AS last_comment,
    SOME_FUNCTION(comment_text) OVER wnd AS number_of_comments
FROM comments
WINDOW wnd AS (
    PARTITION BY post_id
    ORDER BY comment_created_at ASC
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
);

SOME_FUNCTION应该是什么?

它就在你的问题中,一旦你意识到你可以将它与 windows 一起使用:COUNT(*) OVER wnd AS number_of_comments 就可以了。

SELECT DISTINCT
    post_id.
    first_value(comment_text) OVER wnd AS first_comment,
    nth_value(comment_text, 2) OVER wnd AS second_comment,
    last_value(comment_text) OVER wnd AS last_comment,
    COUNT(*) OVER wnd AS number_of_comments
FROM comments
WINDOW wnd AS (
    PARTITION BY post_id
    ORDER BY comment_created_at ASC
    ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
);