【发布时间】:2021-02-19 06:38:47
【问题描述】:
我有一张表,其中包含与一个 ID 相关的许多记录,我只需要为每个 ID 选择具有最近 StartDate 的记录。我怎样才能简单地做到这一点? 例如,对于 id 5001145,我只需要选择开始日期为 2020-03-20 的行。
【问题讨论】:
标签: sql sql-server-2008 select
我有一张表,其中包含与一个 ID 相关的许多记录,我只需要为每个 ID 选择具有最近 StartDate 的记录。我怎样才能简单地做到这一点? 例如,对于 id 5001145,我只需要选择开始日期为 2020-03-20 的行。
【问题讨论】:
标签: sql sql-server-2008 select
一个简单的方法是关联子查询:
select t.*
from t
where t.startdate = (select max(t2.startdate)
from t t2
where t2.id = t.id
);
另一个变体是row_number():
select t.*
from (select t.*,
row_number() over (partition by id order by startdate desc) as seqnum
from t
) t
where seqnum = 1;
【讨论】:
(id, startdate) 上有索引,这可能会快一点。