2014-01-16 30 views
0

我想知道如何根據相同的名字和姓氏刪除所有重複的聯繫人。我知道我必須按名字,姓氏和CustomerID進行分組,但不能弄清楚:在每個組中,我如何確保不會將重複設置刪除到Primary。從數據庫中刪除重複的聯繫人,但不在分組重複中總是保留主要

我知道這與將主小組作爲組中的第一個小組相關,然後刪除除第1行以外的每個組中的所有內容。

以下是我有:

Select * 
FROM CustomerContacts 
WHERE CustomerContactID NOT IN 
(
    SELECT MAX(CustomerContactID) 
    FROM CustomerContacts 
    GROUP BY ContactFirstName, ContactLastName, CustomerID 
) 
+0

您如何識別「主」聯繫?你的SQL不提供任何提示。 –

回答

1

如果你想刪除除了一個ID最大的一切,再下面是「概念」,你想做什麼:

delete from CustomerContacts 
    where CustomerContractsId <> (select max(CustomerContactId) 
            from CustomerContacts cc2 
            where cc2.ContactFirstName = CustomerContacts.ContactFirstName and 
             cc2.ContactLastName = CustomerContacts.ContactLastName and 
             cc2.CustomerId = CustomerContacts.CustomerId 
           ); 

儘管這是標準SQL,但某些數據庫的語法可能略有不同。

EDIT(基於評論):

下獲取ID時primary是真實的,或者,如果沒有,那麼最大的ID:

delete from CustomerContacts 
    where CustomerContractsId <> (select coalesce(max(case when primary then CustomerContactId end), max(CustomerContactId)) 
            from CustomerContacts cc2 
            where cc2.ContactFirstName = CustomerContacts.ContactFirstName and 
             cc2.ContactLastName = CustomerContacts.ContactLastName and 
             cc2.CustomerId = CustomerContacts.CustomerId 
           ); 
+0

我不確定這是否解決了我的問題,如果我錯了,請糾正我。在分組重複中,我想確保將其設置爲Primary = True而不是任何其他分組。如果沒有重複項被設置爲Primary = True,那麼保存哪個重複項並不重要。因此,我想保存其中的一個副本,但如果其中一個是Primary = True,那麼這個副本優先。 – JTunney

+0

完美!謝謝sooooo多! – JTunney