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

PostgreSQL分组聚合:按name和type分组获取url1最新值

PostgreSQL 分组获取最新记录并保留指定字段

问题分析

你需要按name和type分组,获取每组中最新date对应的url1、url2、date,同时保留该组的max(days)。原SQL因为把url1、url2加入分组条件,导致同一name+type下不同url1被拆分成不同组,不符合需求。

解决方案

方法1:窗口函数(推荐)

通过ROW_NUMBER()窗口函数给每个name+type组内的记录按date倒序编号,取编号为1的最新记录,同时计算该组的最大days:

WITH ranked_data AS (
    SELECT 
        name,
        type,
        url1,
        url2,
        date,
        days,
        ROW_NUMBER() OVER (PARTITION BY name, type ORDER BY date DESC) AS rn,
        MAX(days) OVER (PARTITION BY name, type) AS max_days
    FROM your_table_name
)
SELECT name, type, url1, url2, date, max_days
FROM ranked_data
WHERE rn = 1;

方法2:子查询关联

先查询每个name+type组的最新date和最大days,再关联原表获取对应行的url1、url2:

SELECT 
    t.name,
    t.type,
    t.url1,
    t.url2,
    t.date,
    g.max_days
FROM your_table_name t
JOIN (
    SELECT 
        name,
        type,
        MAX(date) AS latest_date,
        MAX(days) AS max_days
    FROM your_table_name
    GROUP BY name, type
) g ON t.name = g.name AND t.type = g.type AND t.date = g.latest_date;

注意事项

  • 替换your_table_name为你的实际表名
  • 若同一name+type组存在多条相同最新date的记录,ROW_NUMBER()会随机取一条;如需保留所有同最新日期的记录,可改用RANK()函数
  • 示例数据执行后结果:
    nametypeurl1url2datemax_days
    Firstonlinehttp2.abclink12022-01-254
    Secondofflinehttp10.xyzlink232r42022-01-121

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:55:19