简体   繁体   中英

How To Get the Last Record in a MySQL Group

I need some help with this: Assume I have the following records:

Driver  Date    Consultant
1   1/01/2010   A
1   3/04/2010   A
1   3/04/2010   A
1   25/06/2012  B
2   24/03/2012  C
3   13/01/2012  A
3   15/01/2012  B
3   15/01/1012  C

Date and Consultant come from the QUOTES Table, The Driver comes from the DRIVER table. Related by the Driver ID.

I need to get the results set to look as follows:

Driver  Quote Count First date  Last Date   Consultant
1          4        1/01/2010   25/06/2012  B
2          1        24/03/2012  24/03/2012  C
3          3        13/01/2012  15/01/1012  C

In MySQL, how do I get the consultant in the results set to be the last consultant that worked on the QUOTE?

Can do this with an explicit join:

select q.*, t.consultant
from (select driver, count(*) as quotecount, min(date) as FirstDate, max(date) as lastdate
      from t
      group by driver
     ) q join
     t
     on t.driver = q.driver and t.date = q.lastdate

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