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()函数 - 示例数据执行后结果:
name type url1 url2 date max_days First online http2. abclink1 2022-01-25 4 Second offline http10. xyzlink232r4 2022-01-12 1
内容的提问来源于stack exchange,提问作者user20128530
相关产品推荐
相关产品推荐

