Postgresql提取每个id的最后一行

时间:2020-12-03 12:28:16

Suppose I've next data

假设我有下一个数据

  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

I want for each id extract last information:

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

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

How could I manage that?

我怎么能管理呢?

3 个解决方案

#1


33  

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

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

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.

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

#2


8  

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

Tested in PostgreSQL,MySQL

在PostgreSQL,MySQL中测试过

#3


-1  

Group by id and use any aggregate functions to meet the criteria of last record. For example

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

select  id, max(date), another_info
from the_table
group by id, another_info

#1


33  

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

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

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.

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

#2


8  

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

Tested in PostgreSQL,MySQL

在PostgreSQL,MySQL中测试过

#3


-1  

Group by id and use any aggregate functions to meet the criteria of last record. For example

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

select  id, max(date), another_info
from the_table
group by id, another_info