保留前100条记录,从表中删除记录

时间:2015-03-18 15:59:15

标签: sql-server

我想保留最新的100条记录(lastmodifiedtime是一个日期时间列)并删除剩余的记录。 我正在努力为此目的进行查询。

 ;WITH CTE AS
 (
 SELECT TOP 100 *
 FROM [mytable]
 ORDER BY LastModifiedTime desc
 )
  DELETE FROM CTE
  • 此查询删除前100条记录。我其实想保留它们。

4 个答案:

答案 0 :(得分:3)

这样的查询将为您提供最新100条记录的ID:

SELECT TOP 100 ID
FROM [YOUR_TABLE]
ORDER BY lastmodifiedtime DESC

所以你要做的就是从你的删除中排除这些ID:

DELETE FROM [YOUR_TABLE]
WHERE ID NOT IN 
      (SELECT TOP 100 Id
       FROM [YOUR_TABLE]
       ORDER BY lastmodifiedtime DESC)

只需将ID替换为您的识别字段,将[YOUR_TABLE]替换为您的表名。

答案 1 :(得分:1)

坚持CTE理念,您可以利用ROW_NUMBER功能:

WITH cte AS (
    SELECT ROW_NUMBER() OVER(ORDER BY LastModifiedTime DESC) AS RowNum
        FROM [mytable]
)
DELETE FROM cte
    WHERE RowNum > 100;

答案 2 :(得分:0)

- 假设ean是x1中的唯一键列

with o1 as (select Top 100 ean from x1 order by DATE1)
 delete from x1 where ean not in (select ean from o1)

答案 3 :(得分:0)

还没有人使用过偏移量,所以我想我已经投入了两美分!

; WITH cte_Offset (
SELECT myTableID
  FROM [myTable]
 ORDER BY LastModifiedTime Desc
OFFSET 100 ROWS )

DELETE 
  FROM myTable 
 WHERE myTableID IN (SELECT myTableID FROM cte_Offset)