我们说我有一张客户地址表:
CName | AddressLine
-------------------------------
John Smith | 123 Nowheresville
Jane Doe | 456 Evergreen Terrace
John Smith | 999 Somewhereelse
Joe Bloggs | 1 Second Ave
我想选择具有明显地址的CName意味着我不想选择" John Smith"因为它有两个地址。我该怎么做?
答案 0 :(得分:1)
使用:
SELECT CName
FROM Addresses
GROUP BY CName
HAVING COUNT(DISTINCT AddressLine) = 1
答案 1 :(得分:1)
您可以通过执行以下操作获取不同的行:
select cname, min(AddressLine) as AddressLine
from t
group by cname
having count(*) = 1;
答案 2 :(得分:1)
或者,您可以使用WHERE NOT EXISTS
:
Select CName, AddressLine
From YourTable A
Where Not Exists
(
Select *
From YourTable B
Where A.CName = B.CName
And A.AddressLine <> B.AddressLine
)
编辑以解决效果:
Create Table Test (CName Varchar (20), AddressLine Varchar (50));
Insert Test Values
('John Smith', '123 Nowheresville'),
('Jane Doe', '456 Evergreen Terrace'),
('John Smith', '999 Somewhereelse'),
('Joe Bloggs', '1 Second Ave')
select cname, min(AddressLine) as AddressLine
from test
group by cname
having count(*) = 1;
Select CName, AddressLine
From Test A
Where Not Exists
(
Select *
From Test B
Where A.CName = B.CName
And A.AddressLine <> B.AddressLine
);
执行计划:
答案 3 :(得分:0)
试试这个:
SELECT a.CName
FROM Addresses a
GROUP BY a.CName
HAVING COUNT(a.AddressLine) = 1