如果不等于则仅获取一行

时间:2019-02-12 01:38:27

标签: sql sql-server

我有我的桌子:

ID | NAME | TYPE             
1  | A    | 1    
2  | A    | NULL  
3  | B    | NULL  
4  | C    | 2    
5  | D    | NULL 
6  | D    | NULL   

例如,如果我选择Type 1,我想得到该行,但我要从另一个中得到所有空值。

ID | NAME | TYPE             
1  | A    | 1    
3  | B    | NULL  
5  | D    | NULL 
6  | D    | NULL   

有时候是这样。我尝试使用工会,但我得到重复 A | NULL

thx全部

1 个答案:

答案 0 :(得分:4)

您似乎想要:

select t.*
from t
where type = 1
union all
select t.*
from t
where type is null and
      not exists (select 1 from t t2 where t2.name = t.name and t2.type = 1);

您实际上并不需要union all

select t.*
from t
where type = 1 or
      (type is null and
       not exists (select 1 from t t2 where t2.name = t.name and t2.type = 1)
      );