【问题标题】:Exact only one date for idid只有一个日期
【发布时间】:2021-02-19 06:38:47
【问题描述】:

我有一张表,其中包含与一个 ID 相关的许多记录,我只需要为每个 ID 选择具有最近 StartDate 的记录。我怎样才能简单地做到这一点? 例如,对于 id 5001145,我只需要选择开始日期为 2020-03-20 的行。

【问题讨论】:

    标签: sql sql-server-2008 select


    【解决方案1】:

    一个简单的方法是关联子查询:

    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;
    

    【讨论】:

    • 非常感谢,有没有可能在select中不显示行号(sequm)?
    • @sear1234 。 . .您可以选择您想要的列或使用第一种方法(如果您在 (id, startdate) 上有索引,这可能会快一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 1970-01-01
    • 2021-03-02
    • 2023-03-03
    • 2011-07-04
    • 2019-05-25
    • 1970-01-01
    相关资源
    最近更新 更多