0

我有一个包含许多时间戳条目的表(名为“DATED”的时间戳列)。

我定期希望从表中删除比 DATED 列中最后 24 个不同日期更早的旧条目。

所以我正在尝试编写一个删除查询 who's where 子句解析为 (DATED < [The 24th Distinct Date from DATED])

我不想设计查询来删除早于 x 天的记录。我希望该表始终保持 24 个记录集,即使它们是旧记录。

有什么建议吗?

4

2 回答 2

3

With the help of Coomon Table Expression and Window Function you can get what you desired.

For 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

For 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
于 2013-04-04T13:49:13.857 回答
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
)
于 2013-04-04T13:55:19.183 回答