简体   繁体   中英

MySQL Select one row per ID according to highest submitted date per ID

I have the table:

id | date_submitted
 1  | 01/01/2017
 1  | 01/02/2017
 2  | 01/03/2017
 2  | 01/04/2017

I'm looking for the correct SQL to select each row, limited to one row per id that has the latest value in date_submitted .

So the SQL should return for the above table:

 id | date_submitted
 1  | 01/02/2017
 2  | 01/04/2017

The query needs to select everything in the row, too.

Thanks for your help.

You can find max date for each id in subquery and join it with the original table to get all the rows with all the columns (assuming there are more columns apart from id and date_submitted) like this:

select t.*
from your_table t
inner join (
    select id, max(date_submitted) date_submitted
    from your_table
    group by id
) t2 on t.id = t2.id
and t.date_submitted = t2.date_submitted;

Note that this query will return multiple rows for an id in case there are multiple rows with date_submitted equals to max date_submitted for that id. If you really want only one row per id, then the solution will be a bit different.

If you just need id and max date use:

select id, max(date_submitted) date_submitted
from your_table
group by 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