2015-02-10 117 views
0

我想要獲取具有相同電話號碼的客戶列表,因爲有相同客戶的實例創建了兩次或三次,名稱略有不同。加入SQL表並刪除重複

查詢下面已經幾乎是預期的行爲:

SELECT C1.CUSTOMER_NAME, C2.CUSTOMER_NAME, C1.PHONE_NUMBER 
FROM CUSTOMER C1 
JOIN CUSTOMER C2 
ON C1.PHONE_NUMBER = C2.PHONE_NUMBER 
WHERE C1.CUSTOMER_NAME != C2.CUSTOMER_NAME 
AND C1.PHONE_NUMBER != '' 
ORDER BY C1.CUSTOMER_NAME 

,但我得到repetions這樣的:

Customer A - Customer B 
Customer A - Customer C 
Customer B - Customer A 
Customer B - Customer C 
Customer C - Customer A 
Customer C - Customer B 

當所有我想要得到的是前兩行,這是足以覆蓋所有的情況。

在此先感謝您的幫助。

+0

明確你想要它的位混淆寫希望的結果,並提供你的結果集。 – 2015-02-10 16:43:45

回答

2

我不確定你只想要前兩行。 。 。因爲最後一行似乎不同。

在任何情況下,你可以用<代替!=得到你想要的東西:

SELECT C1.CUSTOMER_NAME, C2.CUSTOMER_NAME, C1.PHONE_NUMBER 
FROM CUSTOMER C1 JOIN 
    CUSTOMER C2 
    ON C1.PHONE_NUMBER = C2.PHONE_NUMBER AND 
     C1.CUSTOMER_NAME < C2.CUSTOMER_NAME 
WHERE C1.PHONE_NUMBER <> '' 
ORDER BY C1.CUSTOMER_NAME; 

如果你只是想所有在指定電話號碼的客戶 - 當有多個客戶 - - 那麼你並不需要一個join

select c.phone_number, c.name 
from (select c.*, count(*) over (partition by phone_number) as cnt 
     from customer c 
    ) c 
where cnt > 1 
order by c.phone_number, c.name; 
+0

你是對的,最後一種情況是不同的,但當他們更新A,B和C的電話號碼時,最後一種情況也將被修復。我更喜歡最好的解決方案,只是因爲它更接近我期待的內容,但第二個解決方案也能正常工作。謝謝。 – fpele 2015-02-10 16:52:17

2

你可以使用子查詢(或具有相同的登錄JOIN),以獲得重複的號碼,然後再對所有的客戶與數報告:

SELECT CUSTOMER_NAME, PHONE_NUMBER 
FROM CUSTOMER 
WHERE PHONE_NUMBER IN (SELECT PHONE_NUMBER 
         FROM CUSTOMER 
         WHERE COUNT(PHONE_NUMBER) > 1 AND PHONE_NUMBER != '') 
ORDER BY PHONE_NUMBER