PostgreSQL - fetch the row which has the Max value for a column

前端 未结 9 847
感动是毒
感动是毒 2020-11-28 18:38

I\'m dealing with a Postgres table (called \"lives\") that contains records with columns for time_stamp, usr_id, transaction_id, and lives_remaining. I need a query that wil

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 19:29

    I would propose a clean version based on DISTINCT ON (see docs):

    SELECT DISTINCT ON (usr_id)
        time_stamp,
        lives_remaining,
        usr_id,
        trans_id
    FROM lives
    ORDER BY usr_id, time_stamp DESC, trans_id DESC;
    

提交回复
热议问题