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

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

    Here's another method, which happens to use no correlated subqueries or GROUP BY. I'm not expert in PostgreSQL performance tuning, so I suggest you try both this and the solutions given by other folks to see which works better for you.

    SELECT l1.*
    FROM lives l1 LEFT OUTER JOIN lives l2
      ON (l1.usr_id = l2.usr_id AND (l1.time_stamp < l2.time_stamp 
       OR (l1.time_stamp = l2.time_stamp AND l1.trans_id < l2.trans_id)))
    WHERE l2.usr_id IS NULL
    ORDER BY l1.usr_id;
    

    I am assuming that trans_id is unique at least over any given value of time_stamp.

提交回复
热议问题