如何在SQL Server中保留最新记录并删除旧记录?

时间:2016-01-08 07:08:59

标签: sql sql-server

我的表按照这样的desc值排序

aaa  12am
aaa  11am
bbb  12am
bbb  11am

我需要删除第2行和第4行并保留最新的

1 个答案:

答案 0 :(得分:6)

您可以使用CTE ROW_NUMBER

来执行此操作
;WITH ToDelete AS (
   SELECT ROW_NUMBER() OVER (PARTITION BY name ORDER BY timefield DESC) AS rn
   FROM mytable
)
DELETE FROM ToDelete
WHERE rn > 1

rn=1标识每个切片的最新记录。在CTE上执行的删除操作将传播到真实表,并删除所有最新记录。

修改

要为每张幻灯片使用选择最新记录:

;WITH CTE AS (
   SELECT *,
          ROW_NUMBER() OVER (PARTITION BY name 
                             ORDER BY timefield DESC) AS rn
   FROM mytable
)
SELECT * 
FROM CTE
WHERE rn = 1