PostgreSQL提取每个ID的最后一行 [英] Postgresql extract last row for each id

查看:348
本文介绍了PostgreSQL提取每个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提取最新信息:

I want for each id extract last information:

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

我该如何处理?

推荐答案

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

The most efficient way is to use Postgres' distinct on operator

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

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

If you want a solution that works across databases (but is less efficient) you can use a window function:

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;

带有窗口功能的解决方案在大多数情况下比使用子查询要快。

The solution with a window function is in most cases faster than using a sub-query.

这篇关于PostgreSQL提取每个ID的最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆