2016-08-16 93 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) 
相關問題