在 SQL 中,当它可能有两个不同的观察结果时,我如何 select 唯一用户 ID?

In SQL, how do I select unique user id when it may have two different observations?

我有一个 table,其中包含人员姓名和国籍。一个人可能有双重国籍,但如果他们有美国国籍,我只想要那个人的那一行。

例如:\

Name   Citizenship\
John       US\
John      England\
Jim       Germany\
Mark      US\
Mark      Belgium

预期输出

Name    Country\
John     US\
Jim      Germany\
Mark     US

提前感谢您的帮助。

NOT EXISTS:

select t.* from tablename t
where t.citizenship = 'US'
or not exists (select 1 from tablename where name = t.name and citizenship = 'US')

或使用 FIRST_VALUE() window 函数:

select distinct name,
       first_value(citizenship) 
       over (partition by name order by case when citizenship = 'US' then 1 else 2 end) citizenship
from tablename

参见demo
结果:

> Name | Citizenship
> :--- | :----------
> John | US         
> Jim  | Germany    
> Mark | US  

您可以使用 ROW_NUMBER() window 函数,如:

select *
from (
  select name, citizenship,
    row_number() over(partition by name 
      order by case when citizenship = 'US' then 1 else 2 end, citizenship
    ) as rn
  from t 
) x
where rn = 1

这是一种口味:

SELECT DISTINCT
    Name,
    Citizenship= CASE WHEN COUNT(CASE WHEN Citizenship = 'US' THEN 1 ELSE 0 END) OVER (PARTITION BY Name) > 1 THEN 'US' ELSE Citizenship END
FROM 
    t