2012-10-17 140 views
3

可能重複:
delete duplicate records in SQL ServerTSQL查詢,刪除所有重複的記錄,但一個

我有哪些獨特的記錄是由複合鍵表示一個表,如(COL_ACOL_B)。

我已經檢查,證實我有重複行我的表使用以下查詢:

select COL_A, COL_B, COUNT(*) 
from MY_TABLE 
group by COL_A, COL_B 
having count(*) > 1 
order by count(*) desc 

現在,我想刪除所有重複的記錄,但只保留一個。

有人可以請說明如何實現這與2列?

編輯: 假設表只有COL_ACOL_B

+1

其餘列是否相同?你如何決定你想保留哪個? – FJT

+0

@FionaT,在這種情況下,只要我保留一個,我不關心我保留哪一個。這是因爲它們都有相同的(COL_A,COL_B)對。爲了簡單起見,只有COL_A和COL_B。 – czchlong

+1

如果您沒有其他字段(希望是關鍵字段),那麼您的刪除語句將刪除所有記錄。你必須有另一個領域來區分記錄。 –

回答

2

1解決方案, 它是靈活的,因爲你可以比COL_ACOL_B添加更多的列:

-- create table with identity filed 
-- using idenity we can decide which row we can delete 
create table MY_TABLE_COPY 
(
    id int identity, 
    COL_A varchar(30), 
    COL_B varchar(30) 
    /* 
    other columns 
    */ 
) 
go 
-- copy data 
insert into MY_TABLE_COPY (COL_A,COL_B/*other columns*/) 
select COL_A, COL_B /*other columns*/ 
from MY_TABLE 
group by COL_A, COL_B 
having count(*) > 1 
-- delete data from MY_TABLE 
-- only duplicates (!) 
delete MY_TABLE 
from MY_TABLE_COPY c, MY_TABLE t 
where c.COL_A=t.COL_A 
and c.COL_B=t.COL_B 
go 
-- copy data without duplicates 
insert into MY_TABLE (COL_A, COL_B /*other columns*/) 
select t.COL_A, t.COL_B /*other columns*/ 
from MY_TABLE_COPY t 
where t.id = (
       select max(id) 
       from MY_TABLE_COPY c 
       where t.COL_A = c.COL_A 
       and t.COL_B = c.COL_B 
      ) 
go 

第二個解決方案 如果你真的有兩個col在MY_TABLE UMNS你可以使用:

-- create table and copy data 
select distinct COL_A, COL_B 
into MY_TABLE_COPY 
from MY_TABLE 
-- delete data from MY_TABLE 
-- only duplicates (!) 
delete MY_TABLE 
from MY_TABLE_COPY c, MY_TABLE t 
where c.COL_A=t.COL_A 
and c.COL_B=t.COL_B 
go 
-- copy data without duplicates 
insert into MY_TABLE 
select t.COL_A, t.COL_B 
from MY_TABLE_COPY t 
go 
+0

您可以在INSERT中將SELECT DISTINCT用於MY_TABLE_COPY。然後,在重新插入它們時,您不需要子查詢中的where子句。爲了解決缺乏獨特性而投票。 –

+0

@Data男按摩師謝謝。是的,我可以使用'SELECT DISTINCT',但是如果在MY_TABLE中有兩個以上的列,它將會工作。 – Parado

+0

@DataMasseur我編輯與您的建議的職位。 – Parado

1

嘗試:

-- Copy Current Table 
SELECT * INTO #MY_TABLE_COPY FROM MY_TABLE 

-- Delte all rows from current able 
DELETE FROM MY_TABLE 

-- Insert only unique values, removing your duplicates 
INSERT INTO MY_TABLE 
SELECT DISTINCT * FROM #MY_TABLE_COPY 

-- Remove Temp Table 
DROP TABLE #MY_TABLE_COPY 

只要從MY_TABLE刪除行,當你不打破任何外鍵這應該工作。