Ofe*_*rBr 6 sql postgresql window-functions
使用窗口时,如何获取当前分区的大小(行数)?
例如,假设我有一个表,其中包含博客中帖子的评论。我想知道每个帖子的第一条评论、第二条评论、最后一条评论和评论数是什么(没有另一个子查询,我按 post 和 do 分组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
);
Run Code Online (Sandbox Code Playgroud)
应该SOME_FUNCTION是什么?
小智 5
一旦您意识到可以将它与 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
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
960 次 |
| 最近记录: |