保留表中今天日期以来的最新记录

时间:2019-03-07 20:38:20

标签: sql sql-update sql-server-2016 sql-delete getdate

我需要有关计划在SSIS中使用的更新/删除语句的帮助。我有以下记录表:

Record   DateCreated   TimeCreated
1          3/7/19       11:00AM
2          3/7/19       8:00AM
3          2/5/19       9:00AM
4          2/6/19       10:00AM

我想更新表格,以便保留“今天的日期”(3/7/19)的最新记录,但从“今天的日期”中删除较旧的记录。

更新后,该表应如下所示:

Record   DateCreated   TimeCreated
1          3/7/19       11:00AM
3          2/5/19       9:00AM
4          2/6/19       10:00AM

如果“今天的日期”上有2条以上的记录(例如3、4等),我希望它保留最近的记录。

有人可以帮我提供所需的更新/删除声明吗?

1 个答案:

答案 0 :(得分:2)

您可以使用可更新的CTE:

with todelete as (
      select t.*,
             row_number() over (partition by datecreated order by timecreated desc) as seqnum
      from t
     )
delete from todelete
    where seqnum > 1 and
          datecreated = convert(date, getdate());