MySQL query, MAX() + GROUP BY

后端 未结 7 858
不思量自难忘°
不思量自难忘° 2020-11-27 05:16

Daft SQL question. I have a table like so (\'pid\' is auto-increment primary col)

CREATE TABLE theTable (
    `pid` INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
          


        
7条回答
  •  时光取名叫无心
    2020-11-27 05:47

    (Tested in PostgreSQL 9.something)

    Identify the rid and timestamp.

    select rid, max(timestamp) as ts
    from test
    group by rid;
    
    1   2011-04-14 18:46:00
    2   2011-04-14 14:59:00
    

    Join to it.

    select test.pid, test.cost, test.timestamp, test.rid
    from test
    inner join 
        (select rid, max(timestamp) as ts
        from test
        group by rid) maxt
    on (test.rid = maxt.rid and test.timestamp = maxt.ts)
    

提交回复
热议问题