【问题标题】:Delete Distinct column and latest date of other column删除不同列和其他列的最新日期
【发布时间】:2020-01-19 19:37:18
【问题描述】:

我有一个表,其中主键是 ID 和日期的复合键。有没有办法可以删除 ID 匹配且日期为最新日期的单行?

我是 SQL 新手,所以我尝试了一些方法,但我要么没有得到我正在寻找的结果,要么无法获得正确的语法

DELETE FROM Master 
WHERE ((Identifier = 'SomeID') 
  AND (EffectiveDate = MAX(EffectiveDate));

有多个列具有相同的 ID,但日期不同,即。

ID        EffectiveDate
-------------------------
A         '2019-09-18'
A         '2019-09-17'
A         '2019-09-16'

有没有办法只删除带有A | '2019-09-18' 的行?

【问题讨论】:

    标签: sql sql-server sql-delete


    【解决方案1】:

    您可以使用窗口函数和可更新的 CTE:

    with todelete as (
          select t.*, row_number() over (partition by id order by effective_date desc) as seqnum
          from t
         )
    delete from todelete
        where seqnum = 1;
    

    注意:如果要将其限制为单个 id,请确保在子查询或外部查询中包含 where id = 'a'

    【讨论】:

      【解决方案2】:

      使用 row_number()

      delete from (select *, row_number() over(partition by id order by effectivedate desc) rn from table_name
      ) a where a.rn=1
      

      【讨论】:

        【解决方案3】:

        相关的子查询可能会完成工作:

        DELETE FROM Master 
        WHERE 
            Identifier = 'SomeID'
            AND EffectiveDate = (
                SELECT MAX(EffectiveDate) FROM Master WHERE Identifier = 'SomeID'
            )
        ;
        

        【讨论】:

          【解决方案4】:

          使用 CTE 函数删除行,但下面的查询不会删除那些 ID 的最大日期记录,其中存在单个记录。

          with todelete as (
                select t.*, row_number() over (partition by id order by effective_date desc) as seqnum
                from t
               )
          delete from todelete
              where seqnum = 1 and id  in(select distinct id from todelete where seqnum<>1)
          

          【讨论】:

            【解决方案5】:

            所有 ID 的相关子查询:

            delete table1
            from table1 t1
            where t1.EffectiveDate =
            (
            select max(t2.EffectiveDate)
            from table1 t2
            where t2.ID = t1.ID
            )
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2016-10-30
              • 2018-11-19
              • 2015-11-03
              • 1970-01-01
              • 1970-01-01
              • 2012-05-22
              • 1970-01-01
              相关资源
              最近更新 更多