简体   繁体   中英

In Postgres, how do I select rows from my table with the most recent date?

I'm using Postgres 9.5. I have a table with a few columns ...

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

There could be multiple entries for the crypto_currency_id . My question is, how do I select only the most recent entries for each unique crypto_currency_id in the table? So for instance, if my table contained the entries

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

I would want the query to return two rows, which would be

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

The most efficient way in Postgres is distinct on :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM