删除唯一列和其他列的最新日期

时间:2019-09-18 19:31:27

标签: sql sql-server sql-delete

我有一个表,其中主键是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'删除行?

5 个答案:

答案 0 :(得分:0)

您可以使用窗口功能和可更新的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'

答案 1 :(得分:0)

使用row_number()

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

使用CTE功能删除该行,但下面的查询不会删除存在该ID的那些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)

答案 4 :(得分:0)

具有针对所有ID的相关子查询:

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