简体   繁体   中英

Select the latest entries by date grouped by serial

I'm trying to select the latest entry for each serial, ignoring all other entries from a MySQL database. The SQL command I am currently using is:

SELECT *,MAX(date) FROM `gps-log` GROUP BY serial DESC

This is returning only one entry per serial (perfect), but is fetching the first entry, not the latest, as per below sample. The correct maximum date is identified, but that record isn't fetched for some reason.

pos                       elev    serial      date                  MAX(date)
-33.8710138,151.1924356   54.0m   SDGH23465   2012-09-26 17:01:59   2012-09-27 12:14:23
-33.8707848,151.1925109   54.0m   SDGH29648   2012-09-27 12:14:30   2012-09-27 12:21:41

I tried adding DESC to the query, but that only rearranged the output (predictably), not the actual rows fetched. I've looked at a whole bunch of different questions but most deal with either multiple tables or grouping by more complex things such as date which I can't seem to follow in any way that allows me to get this query working correctly.

I'm obviously missing something here that tells the query how to get the right sequence, so any help would be greatly appreciated!

Try this,

SELECT  a.*
FROM    `gps-log` a
        INNER JOIN
        (
            SELECT serial, MAX(`date`) maxDate
            FROM `gps-log`
            GROUP BY serial
        ) b ON a.serial = b.serial AND
                a.`date` = b.maxDate

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