显示跨多个列的重复条目的完整记录

时间:2013-06-12 10:38:46

标签: sql duplicates

我有一个表(客户),包括字段telephone_1,telephone_2,telephone_3& telephone_4。

我需要看到的是有关其他客户使用电话号码的完整记录 - 因为我认为某些地方的数据出现问题,而且客户号码相互重复!

我已经尝试了下面的代码,但这并没有给我我想要的东西,因为只比较了1 / 1,2 / 2,3 / 3& 4/4。我有一个ID字段,可用于区分记录。

 SELECT *
 FROM Customers AS a
 WHERE 1 < (SELECT Count(*)
 FROM Customers AS b
 WHERE a.Telephone_1 = b.Telephone_1
  OR a.Telephone_2 = b.Telephone_2
  OR a.Telephone_3 = b.Telephone_3
  OR a.Telephone_4 = b.Telephone_4

感谢任何帮助 - 谢谢!

1 个答案:

答案 0 :(得分:0)

这个怎么样?

SELECT *
FROM Customers AS a
WHERE 1 < (
    SELECT Count(*)
    FROM Customers AS b
    WHERE a.Telephone_1 IN (b.Telephone_1, b.Telephone_2, b.Telephone_3, b.Telephone_4)
    OR a.Telephone_2 IN (b.Telephone_1, b.Telephone_2, b.Telephone_3, b.Telephone_4)
    OR a.Telephone_3 IN (b.Telephone_1, b.Telephone_2, b.Telephone_3, b.Telephone_4)
    OR a.Telephone_4 IN (b.Telephone_1, b.Telephone_2, b.Telephone_3, b.Telephone_4)
)

========选择2 =======

发表评论后:

使用电话号码和客户ID

创建一个新表
CREATE TABLE tempTelephoneNos (
    INTEGER customer,
    VARCHAR(32) telephoneNo
);

假设这些是客户ID和电话号码的适当数据类型

填充新表

INSERT INTO tempTelephoneNos (customer, telephoneNo)
SELECT customer_id, telephone_1
FROM customers
UNION ALL
SELECT customer_id, telephone_2
FROM customers
UNION ALL
SELECT customer_id, telephone_3
FROM customers
UNION ALL
SELECT customer_id, telephone_4
FROM customers

然后,您可以找到为多个客户显示的电话号码

SELECT customer, telephoneNo
FROM tempTelephoneNos
WHERE 1 < (SELECT COUNT(*) FROM tempTelephoneNos GROUP BY telephoneNo)