2017-07-29 54 views
0

我正在使用Postgres 9.5。我有一个表有几列...在Postgres中,如何从表格中选择最近日期的行?

crypto_currency_id | integer      | 
price    | integer      | 
last_updated  | timestamp without time zone | 

有可能是为crypto_currency_id多个条目。我的问题是,如何为表中每个唯一的crypto_currency_id选择最近的条目?因此,举例来说,如果我的表包含的条目

crypto_currency_id  price   last_updated 
===================================================== 
2       50    2017-06-01 
2       52    2017-07-01 
3       500   2017-01-01 

我想查询返回两行,这将是

2       52    2017-07-01 
3       500   2017-01-01 
+0

[根据上次日期选择记录]可能的重复(https://stackoverflow.com/questions/19027881/select-records-based-on-last-date) – Abelisto

回答

0

在Postgres的最有效的方法是distinct on

select distinct on (crypto_currency_id) t.* 
from t 
order by crypto_currency_id, last_updated desc;