加入SQL表并删除重复

时间:2015-02-10 16:39:01

标签: sql sql-server tsql

我正在尝试获取具有相同电话号码的客户列表,因为同一客户的实例创建了两次或三次,名称略有不同。

以下查询几乎具有预期的行为:

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

但是我得到了重复:

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

当我想得到的只是前两行时,足以涵盖所有情况。

提前感谢您的帮助。

2 个答案:

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

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