MySQL query, MAX() + GROUP BY

后端 未结 7 764
不思量自难忘°
不思量自难忘° 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)
    
    0 讨论(0)
  • 2020-11-27 05:47
    select *
    from (
        select `pid`, `timestamp`, `cost`, `rid`
        from theTable 
        order by `timestamp` desc
    ) as mynewtable
    group by mynewtable.`rid`
    order by mynewtable.`timestamp`
    

    Hope I helped !

    0 讨论(0)
  • 2020-11-27 05:49

    If you want to avoid a JOIN, you can use:

    SELECT pid, rid FROM theTable t1 WHERE t1.pid IN ( SELECT MAX(t2.pid) FROM theTable t2 GROUP BY t2.rid);
    
    0 讨论(0)
  • 2020-11-27 06:06

    You could also have subqueries like that:

    SELECT ( SELECT MIN(t2.pid)
             FROM test t2
             WHERE t2.rid = t.rid
               AND t2.timestamp = maxtimestamp
           ) AS pid 
         , MAX(t.timestamp) AS maxtimestamp
         , t.rid
    FROM test t
    GROUP BY t.rid
    

    But this way, you'll need one more subquery if you want cost included in the shown columns, etc.

    So, the group by and join is better solution.

    0 讨论(0)
  • 2020-11-27 06:07
    SELECT t.pid, t.cost, to.timestamp, t.rid
    FROM test as t
    JOIN (
        SELECT rid, max(tempstamp) AS maxtimestamp
        FROM test GROUP BY rid
    ) AS tmax
        ON t.pid = tmax.pid and t.timestamp = tmax.maxtimestamp
    
    0 讨论(0)
  • 2020-11-27 06:08

    Try:

    select pid,cost, timestamp, rid from theTable order by timestamp DESC limit 2;
    
    0 讨论(0)
提交回复
热议问题