0

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
Dave
  • 15,639
  • 133
  • 442
  • 830
  • Possible duplicate of [Select records based on last date](https://stackoverflow.com/questions/19027881/select-records-based-on-last-date) – Abelisto Jul 29 '17 at 22:42

1 Answers1

1

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;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786