我的表按照这样的desc值排序
aaa 12am
aaa 11am
bbb 12am
bbb 11am
我需要删除第2行和第4行并保留最新的
答案 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