简体   繁体   中英

SQL return column A when max column B

I have this table and I want to return the most recent (based upon highest ID) outcome per MID

╔══════╦═══════╦══════╦═════════════════════╦════════╦═════════╗
║ ID   ║  MID  ║ Call ║ Call_Timestamp      ║ Quoted ║ Outcome ║
╠══════╬═══════╬══════╬═════════════════════╬════════╬═════════╣
║ 1957 ║ 31463 ║ Yes  ║ 03/06/2014 11:55:20 ║ No     ║ Yes     ║
║ 1958 ║ 31463 ║ Yes  ║ 04/06/2014 09:43:25 ║ No     ║ No      ║
║ 1959 ║ 31671 ║ Yes  ║ 04/06/2014 10:10:08 ║ Yes    ║ No      ║
║ 1960 ║ 31671 ║ Yes  ║ 04/06/2014 10:10:25 ║ No     ║ Yes     ║
╚══════╩═══════╩══════╩═════════════════════╩════════╩═════════╝

For example I should return

╔══════╦═══════╦══════╦═════════════════════╦════════╦═════════╗
║ ID   ║  MID  ║ Call ║ Call_Timestamp      ║ Quoted ║ Outcome ║
╠══════╬═══════╬══════╬═════════════════════╬════════╬═════════╣
║ 1958 ║ 31463 ║ Yes  ║ 04/06/2014 09:43:25 ║ No     ║ No      ║
║ 1960 ║ 31671 ║ Yes  ║ 04/06/2014 10:10:25 ║ No     ║ Yes     ║
╚══════╩═══════╩══════╩═════════════════════╩════════╩═════════╝ 

Thanks, Rob

Often a not exists query is the most efficient approach:

select t.*
from table t
where not exists (select 1
                  from table t2
                  where t2.mid = t.mid and
                        t2.id > t.id
                 );

This implements the logic: "Get me all rows from the table where there is no row with the same mid and a higher id ". A fancy way of doing what you want.

For performance, an index on table(mid, id) helps.

Create a join on a inline view with the highest id per mid and then get the matching records:

select *
from   tableX t
join   ( select mid
         ,      max(id) max_id
         from   tableX
         group
         by     mid
       ) v
on     v.mid = t.mid
and    v.max_id = t.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM