我有一个包含许多带时间戳的条目的表(Timestamp列名为'DATED')。
我会定期删除早于DATED列中最后24个不同日期的表中的旧条目。
所以我正在尝试编写删除查询 谁的子句解析为(DATED< [从第二十二天开始的日期])
我不想设计查询来删除超过x天的记录。 我希望该表始终保持24个记录集,即使它们是旧记录。
任何建议?
答案 0 :(得分:3)
在Coomon Table Expression
和Window Function
的帮助下,您可以获得所需内容。
对于SQL Server 2005
WITH recordList
AS
(
SELECT *,
DENSE_RANK() OVER (PARTITION BY convert(varchar(20), DATED, 102)
ORDER BY DATED DESC) rn
FROM TableName
)
DELETE FROM recordList
WHERE rn > 24
对于SQL Server 2008 +
WITH recordList
AS
(
SELECT *,
DENSE_RANK() OVER (PARTITION BY CAST(DATED AS DATE)
ORDER BY DATED DESC) rn
FROM TableName
)
DELETE FROM recordList
WHERE rn > 24
答案 1 :(得分:0)
DELETE FROM TABLE
WHERE ID IN
(
SELECT ID
FROM
(
SELECT ID, ROW_NUMBER() OVER (PARTITION BY DATE DESC) RN
FROM TABLE
) A
WHERE RN > 24
)