简体   繁体   English

MySQL根据每个ID的最高提交日期为每个ID选择一行

[英]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 . 我正在寻找正确的SQL以选择每一行,每个id行数限制为date_submitted的最新值。

So the SQL should return for the above table: 因此,SQL应该返回上表:

 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: 您可以在子查询中找到每个id的最大日期,并将其与原始表结合起来,以获取具有所有列的所有行(假设除了id和date_submitted之外还有更多列),如下所示:

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. 请注意,如果存在date_submitted等于该id的最大date_submitted的多行,则此查询将返回ID的多行。 If you really want only one row per id, then the solution will be a bit different. 如果您确实只希望每个id包含一行,那么解决方案将有所不同。

If you just need id and max date use: 如果您只需要ID和最大日期,请使用:

select id, max(date_submitted) date_submitted
from your_table
group by id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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