【问题标题】:sql query to get latest record for each idsql查询获取每个id的最新记录
【发布时间】:2021-01-10 14:29:36
【问题描述】:

我有一张桌子。从那里我需要为每个“id”获取最新的“日期”。我为 One id 编写了查询。但是我不知道如何申请多个id。(我的意思是每个id)

我对一个 id 的查询是(比如表名是 tt):

select * from (SELECT DISTINCT id ,date FROM tt WHERE Trim(id) ='1000082' ORDER BY date desc) where rownum

【问题讨论】:

  • 请用您正在运行的数据库标记您的问题:mysql、oracle、sqlserver...?

标签: sql datetime max greatest-n-per-group


【解决方案1】:

如果你只有两列,聚合就足够了:

select id, max(date) max_date
from mytable
group by id

如果您有更多列,并且希望整个行具有每个 id 的最新日期,那么一个选项使用相关子查询进行过滤:

select t.*
from mytable t
where t.date = (select max(t1.date) from mytable t1 where t1.id = t.id)

如果您的数据库支持,您也可以使用窗口函数:

select *
from (select t.*, row_number() over(partition by id order by date desc) rn from mytable t) t
where rn = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-29
    • 2016-10-15
    • 2021-10-04
    • 1970-01-01
    • 2020-04-09
    • 2011-01-25
    • 2023-01-22
    • 2016-05-15
    相关资源
    最近更新 更多