2016-08-16 95 views
1

我有一个看起来像下面删除SQL重复数据保留最早的条目

Col1 Col2 
------------ 
0010 1111 (Delete this row) 
0011 1112 
0012 1111 (Keep this row) 

我需要删除col2的发现基于Col1中的重复数据行的数据库。我需要保留较旧的条目并删除较年轻的条目。在这个例子中,我需要删除0010保留0012

到目前为止,我有这样的代码,显示我的Col2中重复和显示来自Col1中

唯一编号
Select * 
    From [database] 
    Where (Col2) in (
     Select Col2 
     From [database] 
     Group by Col2 
     Having Count(*) > 1 
    ) 

我不换我的头围绕我需要做的下一步选择正确的Col1号码,以便我可以删除该行。

+1

什么决定在Col1中最古老的...的顺序? –

+0

“我需要保留较旧的条目并删除较新的条目。在此示例中,我需要删除0010并保留0012.”假设Col1是一个序列/自动编号...不会是最古老的,你想保持最新的呢? – xQbert

+0

是的。 Col1永远不会有任何重复的数据,并且每添加一行都会增加1。 – Polarbehr

回答

1
Declare @YourTable table (col1 varchar(25),col2 varchar(25)) 
Insert Into @YourTable values 
('0010','1111'), 
('0011','1112'), 
('0012','1111') 

;with cteBase as (
    Select *,RowNr=Row_Number() over (Partition By Col2 Order By Col1 Desc) from @YourTable 
) 
Select * From cteBase where RowNr>1 
-- Delete From cteBase where RowNr>1 
-- Remove Select if satisfied with results 

条记录被删除

col1 col2 RowNr 
0010 1111 2 
+0

约翰工作完美!非常感谢你。现在我要修复我的文件,然后学习你给我看的东西。 – Polarbehr

+0

@Polarbehr获取窗口函数的舒适。它们非常宝贵。干杯 –

1
WITH cte as 
(
    -- oldest record will always have rn = 1 
    SELECT Col1, Col2, 
      , ROW_NUMBER() OVER(PARTITION by Col2 ORDER BY Col1 DESC) AS rn 
    FROM YourTable 
) 
--Now Delete Duplicate Records 
DELETE FROM cte 
WHERE rn > 1 
1

尝试

delete from [database] d1 
    where exists (select 1 
        from [database] d2 
        where d2.col2 =d1.col2 and d2.col1>d1.col1) 
相关问题