You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL使用聚合函数时如何获取列的最后值

实现思路与查询语句

嘿,这事儿好办!你想在现有的统计结果里加上每个(child, parent)分组的最后一条评论内容,咱们可以用窗口函数来实现,思路很清晰:先给每个(child, parent)分组的评论按“最新”规则排序,标记出每组的第一条(也就是最后发布的那条),再和原来的统计结果关联起来。

修改后的完整查询

WITH ranked_comments AS (
    SELECT
        children.autor AS child,
        parents.autor AS parent,
        children.bodytext,
        -- 按child和parent分组,给每组的评论按commentid降序排号,最新的排第1
        ROW_NUMBER() OVER (PARTITION BY children.autor, parents.autor ORDER BY children.commentid DESC) AS rn
    FROM comments children
    LEFT JOIN comments parents ON children.parentid = parents.commentid
)
SELECT
    stats.child,
    stats.parent,
    stats.count,
    rc.bodytext AS last_comment_content
FROM (
    -- 你原来的统计查询
    SELECT
        children.autor AS child,
        parents.autor AS parent,
        COUNT(*) AS count
    FROM comments children
    LEFT JOIN comments parents ON children.parentid = parents.commentid
    GROUP BY child, parent
    ORDER BY count DESC
    LIMIT 4
) stats
-- 关联到每组的最后一条评论
LEFT JOIN ranked_comments rc 
    ON stats.child = rc.child 
    AND stats.parent = rc.parent 
    AND rc.rn = 1
ORDER BY stats.count DESC;

关键细节说明

  • “最后一条”的定义:这里默认用commentid降序来判断最新评论(假设commentid是自增主键,数值越大发布时间越晚)。如果你的表有专门的创建时间字段(比如created_at),只需要把ORDER BY children.commentid DESC改成ORDER BY children.created_at DESC即可。
  • 窗口函数ROW_NUMBER():它会给每个(child, parent)分组里的评论单独排号,每组里排第1的就是我们要的最后一条评论。
  • 关联逻辑:把原来的统计结果和标记好的最新评论通过child和parent关联,只取rn=1的那条记录的bodytext。

运行这个查询后,你就能得到包含最后一条评论内容的结果啦,比如:

childparentcountlast_comment_content
petermax154这是peter给max的最后一条评论
alexpeter122alex给peter的最新评论内容
............

内容的提问来源于stack exchange,提问作者Alexander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:05:27