仅获取最新数据并从 table 中删除其余数据的有效方法

Efficient way to have only the latest data and delete the rest from a table

我正在尝试找到从我的 Table 中删除数据的最快方法。我的逻辑是对于给定的 Lot_ID,只有 Table1 内的最新 2 天数据,并且 ID 是 Table.

中的唯一主键

我的数据不多,但执行以下查询仍需要大约 8-9 分钟。

WITH CTE AS
(
 select t.ID
from (select t1.*,
             DENSE_RANK() over (partition by Lot_ID order by TRY_CONVERT(DATE, DATEADD(second, t1.starttime, '19700101') )           
              desc) as seqnum
      from  Table1 t1
     ) t
where seqnum >2
)
DELETE Table1 WHERE EXISTS(select 1 from CTE where CTE.ID = Table1.ID )

是否有最快或更好的方法来做到这一点?

您可以尝试直接从 cte 中删除而不是重新打开 table:

with cte as(
    select dense_rank() over (
        partition by lot_id 
        order by try_convert(date, dateadd(second, t1.starttime, '19700101')) desc
    ) as seqnum
    from  table1 t1
)
delete from cte where seqnum > 2

您的查询表明 startime 是纪元时间戳(因此是 int 数据类型),因此另一种可能的优化是使用算术而不是日期转换:

with cte as(
    select dense_rank() over (
        partition by lot_id 
        order by t1.starttime / 60 / 60 / 24 desc
    ) as seqnum
    from  table1 t1
)
delete from cte where seqnum > 2

如果 none 有帮助,那么您可能需要考虑反转逻辑:即将要保留的记录移动到临时 table,然后截断并重新填充原始记录table.