Postgresql 为每个 id 提取最后一行

Postgresql extract last row for each id

假设我有下一个数据

  id    date          another_info
  1     2014-02-01         kjkj
  1     2014-03-11         ajskj
  1     2014-05-13         kgfd
  2     2014-02-01         SADA
  3     2014-02-01         sfdg
  3     2014-06-12         fdsA

我想为每个 id 提取最后的信息:

  id    date          another_info
  1     2014-05-13         kgfd
  2     2014-02-01         SADA
  3     2014-06-12         fdsA

我该如何处理?

最有效的方法是使用 Postgres 的 distinct on 运算符

select distinct on (id) id, date, another_info
from the_table
order by id, date desc;

如果您想要一个跨数据库的解决方案(但效率较低),您可以使用 window 函数:

select id, date, another_info
from (
  select id, date, another_info, 
         row_number() over (partition by id order by date desc) as rn
  from the_table
) t
where rn = 1
order by id;

使用 window 函数的解决方案在大多数情况下比使用子查询更快。

按id分组并使用任何聚合函数来满足最后一条记录的条件。例如

select  id, max(date), another_info
from the_table
group by id, another_info
select * 
from bar 
where (id,date) in (select id,max(date) from bar group by id)

在 PostgreSQL 中测试,MySQL

我发现这是最快的解决方案:

 SELECT t1.*
   FROM yourTable t1
     LEFT JOIN yourTable t2 ON t2.tag_id = t1.tag_id AND t2.value_time > t1.value_time
  WHERE t2.tag_id IS NULL