2014-02-27 56 views
0

我試圖爲每個區域找到唯一的名稱。我有一個(長)名單和地區的名單,我想知道在一個地區發生哪些名字。根據特定標準選擇唯一行的數量

我該如何有效地做到這一點?

的數據是這樣的:

name - region - ... 
Merlangius merlangus - North Atlantic - ... 
Gadus morhua - North Atlantic - ... 
Limanda limanda - North Atlantic - ... 
Merlangius merlangus - North Atlantic - ... 
Limanda limanda - South Atlantic - ... 

輸出應該給我說只發生在一個地區物種的名字和地區。在這種情況下,它應該是這樣的:

name - region - ... 
Merlangius merlangus - North Atlantic - ... 
Gadus morhua - North Atlantic - ... 

謝謝!!

+2

後的表結構和一些樣本數據。做完這些之後,告訴我們預期的產出是多少。但不要停下來,向我們展示你已經嘗試過(查詢)。 –

回答

2

您可以使用 GROUP BYHAVING子句。

事實上,你可以做到這一點

create table test(name varchar(10),region varchar(10)); 

insert into test values('Joe','US'); 
insert into test values('Bill','US'); 
insert into test values('Joe','UK'); 
insert into test values('Stu','US'); 
insert into test values('Stu','UK'); 

Select name from test where name not in (
Select name 
From (
select name,row_number() over(partition by region order by name) as rn 
from test 
)z 
where z.rn>1 
) 

輸出

比爾

這裏是SQL Fiddle DEMO

+0

與問題完全一樣的答案。很公平,真的。 –

+0

@CraigRinger更新了我的答案 –

相關問題