如何找到重复的行,同时又不同?

时间:2013-10-09 06:58:34

标签: sql

我有一个SQL查询问题。

我有一张名字,姓氏和手机号码的表格。

Thor   Prestby   98726364
Thor   Prestby   98726364
Lars   Testrud   12938485
Lise   Robol     12938485

我想找到具有相同手机号码的行,这些行具有不同的名称。如上所示,Thor有两排,这是正确的。 Lars和Lise拥有相同的手机号码,这就是我想要找到的。

6 个答案:

答案 0 :(得分:1)

您几乎已经概述了接受问题所需的行动。

简而言之

  • 使用子选择来获取所有不同的行
  • 来自子选择
  • 的唯一结果集的mobilenumber上的组
  • 仅保留至少出现两次的移动号码

SQL声明

SELECT mobilenumber, COUNT(*)
FROM   (
         SELECT DISTINCT mobilenumber, firstname, lastname
         FROM   YourTable
       ) AS q
GROUP BY
       mobilenumber
HAVING COUNT(*) > 1

答案 1 :(得分:1)

我假设你在这里使用的是MS SQL Server,但你可以使用:

Declare @t table
(
FirstName varchar(100),
LastName varchar(100),
Mobile bigint
)

Insert Into @t
values ('Thor','Prestby',98726364),
        ('Thor','Prestby',   98726364),
        ('Lars','Testrud',12938485),
        ('Lise','Robol', 12938485),
        ('AN','Other', 12345868)

Select Mobile
From @t
Group By Mobile
Having Count(*) > 1

EXCEPT

Select Mobile
From @t
Group By FirstName, LastName, Mobile
Having Count(*) > 1

答案 2 :(得分:0)

SELECT * FROM the_table tt
WHERE EXISTS (
  SELECT * FROM the_table xx
  WHERE xx.mobineno = tt.mobileno
  AND (xx.fname <> tt.fname OR xx.lname <> tt.lname)
  );

答案 3 :(得分:0)

对于此记录:

Thor   Prestby   98726364
Thor   Prestby   98726364
Lars   Testrud   12938485
Lise   Robol     12938485
AN     Other     12345868

试一试:

select  t.mobile, count(*) from new_table t
where t.mobile in
   (select  t1.mobile from new_table t1
     where t1.mobile=t.mobile
    group by   t1.firstname, t1.lastname, t1.mobile
   having count(*)=1)
group by t.mobile
having count(*)>1

你会得到这个结果:

12938485     2

答案 4 :(得分:0)

SELECT t1.phone, count(t1.phone) CountNo
FROM (SELECT distinct * FROM YourTable) t1
Left Outer Join YourTable t2 ON t1.phone = t2.phone AND ( t1.FirstName <> t2.FirstName OR  t1.LastName <> t2.LastName)
WHERE t2.FirstName IS NOT NULL
GROUP BY t1.phone
HAVING count(t1.phone) > 1
ORDER BY CountNo desc

答案 5 :(得分:0)

我使用标准的SQL语法和连接来实现结果

<强>设定:

create table dummy
(
firstname varchar2(20),
lastname varchar2(20),
phone number
);

insert into dummy values('Thor','Prestby',98726364);
insert into dummy values('Thor','Prestby',98726364);
insert into dummy values('Lars','Testrud',12938485);
insert into dummy values('Lise','Robol',12938485);

<强>查询:

select a.firstname,a.lastname,a.phone from dummy a inner join dummy b 
on a.phone=b.phone and a.firstname != b.firstname and a.lastname != b.lastname;

<强>结果

FIRSTNAME            LASTNAME             PHONE                  
-------------------- -------------------- ---------------------- 
Lise                 Robol                12938485               
Lars                 Testrud              12938485