删除SQL中的重复数据,保留最旧的条目

时间:2016-08-16 17:45:55

标签: sql sql-server sqlite

我有一个类似于以下

的数据库
Col1    Col2
------------
0010    1111   (Delete this row)
0011    1112
0012    1111   (Keep this row)

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

到目前为止,我有这段代码向我展示了Col2中的重复项,并显示了Col1中的唯一编号

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

我没有把我的头围绕在我接下来需要做的事情上,以选择正确的Col1号码,所以我可以删除那一行。

3 个答案:

答案 0 :(得分: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 :(得分:1)

尝试

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

答案 2 :(得分: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