使用聚合函数时 Postgresql 列的最后一个值

Ale*_*lex 3 sql postgresql

我有以下工作查询:

select children.autor as child,  parents.autor as parent, count(*) from comments children
left join comments parents on (children.parentid = parents.commentid)
group by child, parent
order by count(*) desc
limit 4;
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

    child           |       parent        | count
peter               | max                 |   154
alex                | peter               |   122
peter               | kARL                |    82
stephen             | alex                |    50
Run Code Online (Sandbox Code Playgroud)

现在评论表还有一个“正文”列,它是实际评论,我想在每对子级和父级的选择中包含最后一条评论。

所以在第一行,我想要彼得在回复 max 时写的最后一条评论。到目前为止,我什至不知道如何处理这个问题。子查询?某种窗口函数?

如果我使用 (max)bodytext,它几乎完全符合我的要求。只是最长的评论并不是我真正想要的。

Joe*_*nek 8

仅将此 1 行添加到您的选择中:

(array_agg(children.bodytext ORDER BY children.commentid DESC))[1] AS last_comment
Run Code Online (Sandbox Code Playgroud)

它将为每个组创建一个包含所有评论的数组,评论将按照指定的顺序(通过 children.commentid DESC)进行排序,然后您只取数组的第一个元素 = 最后一个评论。

全码:

SELECT
  children.autor AS child,
  parents.autor AS parent,
  count(*),
  (array_agg(children.bodytext ORDER BY children.commentid DESC))[1] AS last_comment
FROM
  comments AS children
  LEFT JOIN comments AS parents
    ON (children.parentid = parents.commentid)
GROUP BY child, parent
ORDER BY count(*) DESC;
Run Code Online (Sandbox Code Playgroud)