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

前端 未结 9 869
感动是毒
感动是毒 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:37

    I like the style of Mike Woodhouse's answer on the other page you mentioned. It's especially concise when the thing being maximised over is just a single column, in which case the subquery can just use MAX(some_col) and GROUP BY the other columns, but in your case you have a 2-part quantity to be maximised, you can still do so by using ORDER BY plus LIMIT 1 instead (as done by Quassnoi):

    SELECT * 
    FROM lives outer
    WHERE (usr_id, time_stamp, trans_id) IN (
        SELECT usr_id, time_stamp, trans_id
        FROM lives sq
        WHERE sq.usr_id = outer.usr_id
        ORDER BY trans_id, time_stamp
        LIMIT 1
    )
    

    I find using the row-constructor syntax WHERE (a, b, c) IN (subquery) nice because it cuts down on the amount of verbiage needed.

提交回复
热议问题