0

我有一个 SQL 查询问题。

我有一张桌子,上面有客户的名字、姓氏和手机号码。

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

我想查找具有相同手机号码但名称不同的行。正如您在上面看到的,Thor 有 2 行,没错。Lars 和 Lise 有相同的手机号码,这就是我想要找到的。

4

6 回答 6

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
于 2013-10-09T07:05:56.817 回答
1

您几乎概述了自己在问题中需要采取的行动。

简而言之

  • 使用子选择来获取所有不同的行
  • 来自子选择的这个唯一结果集中的移动号码组
  • 只保留至少出现两次的手机号码

SQL 语句

SELECT mobilenumber, COUNT(*)
FROM   (
         SELECT DISTINCT mobilenumber, firstname, lastname
         FROM   YourTable
       ) AS q
GROUP BY
       mobilenumber
HAVING COUNT(*) > 1
于 2013-10-09T07:03:19.207 回答
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
于 2013-10-09T08:36:01.787 回答
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
于 2013-10-09T08:48:43.283 回答
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  
于 2013-10-09T08:50:04.373 回答
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)
  );
于 2013-10-09T08:25:23.317 回答