在Postgres中,如何从最近的日期中选择表格中的行?

时间:2017-07-29 22:29:47

标签: sql postgresql group-by

我正在使用Postgres 9.5。我有一个有几列的表......

 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

1 个答案:

答案 0 :(得分:0)

Postgres中最有效的方法是distinct on

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