使用相同的信息查找不同列的重复项

时间:2017-08-14 11:52:28

标签: sql-server

我已经尝试使用谷歌搜索,但没有运气。我能找到的所有答案都是列中的不同信息。在这种情况下,我在多列中有相同的信息(电话号码)。

我有一张桌子上有顾客和他们的电话号码。每个客户在三个不同的列(家庭,工作和移动电话)中最多有三个不同的电话号码。手机号码可以用作家庭号码。有些客户拥有与其他客户相同的电话号码,因为他们是夫妻或父母和孩子。在这种情况下,这是不行的。

因此,我需要在手机和家庭电话栏中搜索共享者。 (此处忽略工作电话号码。)

示例表:

ID / Phone home / Phone mobile
1 / 12345678 / 98765432
2 / 12345678 / 22222222
3 / 23456789 / 33333333
4 / 33333333 / 87654321

在上表中,我需要查询返回所有四个客户。 ID 1和ID 2因为它们具有相同的家庭电话号码以及ID 3和ID 4,因为它们在家庭和移动列中具有相同的号码(33333333)。

我至少需要重复的客户ID,但我也希望看到重复的电话号码。

谢谢!

4 个答案:

答案 0 :(得分:1)

我认为你可以使用exists

做你想做的事
select t.*
from t
where exists (select 1
              from t t2
              where t2.id <> t.id and
                    (t2.homephone in (t.homephone, mobilephone) or
                     t2.mobilephone in (t.homephone, mobilephone)
                    )
             );

另一种方法可能会有更好的表现:

select tp.*
from (select t.id, v.phone,
             count(*) over (partition by id) as cnt
      from t cross apply
           (values (t.homephone), (t.mobilephone)) v(phone)
     ) tp
where cnt > 1;

此版本实际上会返回两列中具有相同手机的行。如果这可能是一个问题,这很容易解决。

答案 1 :(得分:1)

我的方法是将查询规范化为Id和Phone,然后进行自联接以查找副本:

WITH [CTE] AS (
    SELECT Id, HomePhone as Phone FROM customers
    UNION 
    SELECT Id, WorkPhone as Phone FROM customers
    UNION
    SELECT Id, MobilePhone as Phone FROM customers
) 
SELECT c1.Id, c2.Id, [c1].[Phone] 
FROM [CTE] AS [c1] INNER JOIN [CTE] AS [c2] 
   ON [c1].[Phone] = [c2].[Phone] AND [c1].[Id] <> [c2].[Id]

答案 2 :(得分:1)

您可以取消数据,然后进行自我加入:

$rules->add($rules->existsIn(['product_id'], 'Products'));  //Validation in the model of Orders.

返回

CREATE TABLE #phone
(
    Id INT,
    HomePhone VARCHAR(20),
    MobilePhone VARCHAR(20)
)

INSERT INTO #phone ( Id, HomePhone, MobilePhone ) VALUES(1, 12345678, 98765432);
INSERT INTO #phone ( Id, HomePhone, MobilePhone ) VALUES(2, 12345678, 22222222);
INSERT INTO #phone ( Id, HomePhone, MobilePhone ) VALUES(3, 23456789, 33333333);
INSERT INTO #phone ( Id, HomePhone, MobilePhone ) VALUES(4, 33333333, 87654321);

WITH unpivoted AS 
(
    SELECT Id, Phone, PhoneType
    FROM #phone
    UNPIVOT
    (
        Phone FOR PhoneType IN (HomePhone, MobilePhone)
    ) AS unpiv
)
SELECT a.id, a.Phone, a.PhoneType, b.Id, b.Phone, b.PhoneType
FROM unpivoted A
INNER JOIN unpivoted B ON A.Phone = B.Phone AND B.Id > A.Id

答案 3 :(得分:0)

如果您提供输出数据的示例,那将会很有帮助。 但请尝试使用EXISTShttps://msdn.microsoft.com/es-es/library/ms188336(v=sql.120).aspx

SELECT *
FROM customers c
WHERE EXISTS (SELECT * 
             FROM customers c2 
             WHERE c.Id != c2.Id 
             AND (
                   (c.HomePhone = c2.HomePhone || c.HomePhone = c2.WorkPhone || c.HomePhone = c2.MobilePhone)
                    || (c.WorkPhone = c2.HomePhone || c.WorkPhone = c2.WorkPhone || c.WorkPhone = c2.MobilePhone)
                    || (c.MobilePhone= c2.HomePhone || c.MobilePhone= c2.WorkPhone || c.MobilePhone= c2.MobilePhone)
             )