可能重复:
How can I find duplicate entries and delete the oldest ones in SQL?
由于更新工具错误,我有一个数千个重复的数据库。我能够识别具有重复项的项集合,但是只需删除最旧的条目,不一定是最低的id。测试数据看起来像这样,正确的行有一个*
除了最近创建的行之外,应删除具有重复标题但没有重复规则的文章。 (实际的id列是一个GUID所以我不能假设自动递增)
Id Article id Rule Id Title Opened Date
-- ---------- ------- ----- -----------
1* 111 5 T1 2013-01-20
2 112 5 T1 2013-07-01
3* 113 6 T2 2013-07-01
4* 114 7 T2 2013-07-02
5 115 8 T3 2012-07-01
6 116 8 T3 2013-01-20
7* 117 8 T3 2013-01-21
表架构:
CREATE TABLE [dbo].[test_ai](
[id] [int] NOT NULL,
[ArticleId] [varchar](50) NOT NULL,
[ruleid] [varchar](50) NULL,
[Title] [nvarchar](max) NULL,
[AuditData_WhenCreated] [datetime] NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)
测试数据插页
insert into test_ai (id, articleid, ruleid, title, auditdata_whencreated) values (1, 111, 5, 'test 1', '2013-01-20')
insert into test_ai (id, articleid, ruleid, title, auditdata_whencreated) values (2, 112, 5, 'test 1', '2012-07-01')
insert into test_ai (id, articleid, ruleid, title, auditdata_whencreated) values (3, 113, 6, 'test 2', '2012-07-01')
insert into test_ai (id, articleid, ruleid, title, auditdata_whencreated) values (4, 114, 7, 'test 2', '2012-07-02')
insert into test_ai (id, articleid, ruleid, title, auditdata_whencreated) values (5, 115, 8, 'test 3', '2012-07-01')
insert into test_ai (id, articleid, ruleid, title, auditdata_whencreated) values (6, 116, 8, 'test 3', '2013-01-20')
insert into test_ai (id, articleid, ruleid, title, auditdata_whencreated) values (7, 117, 8, 'test 3', '2013-01-21')
我当前的查询如下所示
select * from test_ai
where test_ai.id in
-- set 1 - all rows with duplicates
(select f.id
from test_ai as F
WHERE exists (select ruleid, title, count(id)
FROM test_ai
WHERE test_ai.title = F.title
AND test_ai.ruleid = F.ruleid
GROUP BY test_ai.title, test_ai.ruleid
having count(test_ai.id) > 1))
and test_ai.id not in
-- set 2 - includes one row from each set of duplicates
(select min(id)
from test_ai as F
WHERE EXISTS (select ruleid, title, count(id)
from test_ai
WHERE test_ai.title = F.title
AND test_ai.ruleid = F.ruleid
group by test_ai.title, test_ai.ruleid
HAVING count(test_ai.id) > 1)
GROUP BY title, ruleid
)
此SQL标识了应删除的一些行(第2,6,7行),但它确实按“打开日期”选择了最旧的文章。 (应该删除行2,5,6)我意识到我没有在声明中指定这个,但我正在努力解决如何添加这个最后一块。如果它导致我需要多次运行的脚本,以便在有多个重复项时删除重复项,那么这不是问题。
实际问题要复杂得多,但是如果我能够通过这个阻挡部分,我将能够再次前进。谢谢你看看!
答案 0 :(得分:3)
在SQL Server 2005+中从一组(或一组中的每个组)中删除一行的典型模型是:
;WITH cte AS
(
SELECT col, rn = ROW_NUMBER() OVER
(PARTITION BY something ORDER BY something)
FROM dbo.base_table
WHERE ...
)
DELETE x WHERE rn = 1;
在你的情况下,这将是:
;WITH cte AS
(
SELECT id, ruleid, Title, rn = ROW_NUMBER() OVER
(
PARTITION BY ruleid, Title
ORDER BY auditdata_whencreated DESC
)
FROM dbo.test_ai
)
DELETE cte
OUTPUT deleted.id
WHERE rn > 1;
结果:
id
----
2
6
5