简体   繁体   中英

Postgres sql select result based on a ranking derived from a text column

Scratching my head here. I have a very simple postgres table from which I need to select a unique row per day, based solely on a text column which updates as follows.

First update= 'AA1', 2nd update= 'AB', 3rd update= 'D4'

    id  item      date         run    value
    ---------------------------------------
    23  apple     01/01/16      AA1    232
    25  apple     01/01/16      AB     254
    26  apple     01/01/16      D4     212

Depending on the time of day, running a query based on the date ('01/01/2016') would return 1, 2 or 3 rows. However I only need the latest row eg Run = D4 above.

How can I write a simple select query that always returns just the latest row based of a text based column? I presume i need to create a ranking based on the 'run' column but Im not sure how to do this.

regards

Using the handy distinct on :

select distinct on (date) *
from t
order by date, run 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