我有一个 SQL 查询问题。
我有一张桌子,上面有客户的名字、姓氏和手机号码。
Thor Prestby 98726364
Thor Prestby 98726364
Lars Testrud 12938485
Lise Robol 12938485
我想查找具有相同手机号码但名称不同的行。正如您在上面看到的,Thor 有 2 行,没错。Lars 和 Lise 有相同的手机号码,这就是我想要找到的。
我有一个 SQL 查询问题。
我有一张桌子,上面有客户的名字、姓氏和手机号码。
Thor Prestby 98726364
Thor Prestby 98726364
Lars Testrud 12938485
Lise Robol 12938485
我想查找具有相同手机号码但名称不同的行。正如您在上面看到的,Thor 有 2 行,没错。Lars 和 Lise 有相同的手机号码,这就是我想要找到的。
我假设您在这里使用的是 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
您几乎概述了自己在问题中需要采取的行动。
简而言之
SQL 语句
SELECT mobilenumber, COUNT(*)
FROM (
SELECT DISTINCT mobilenumber, firstname, lastname
FROM YourTable
) AS q
GROUP BY
mobilenumber
HAVING COUNT(*) > 1
对于此记录:
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
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
我正在使用标准 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
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)
);