获取同一列中所有对应列为空的记录

时间:2019-03-25 14:09:24

标签: sql sql-server sql-server-2012

我的数据看起来像这样

| id             | Failure            
+----------------+-----------
| 1              | null 
| 1              | null  
| 1              | null  
| 1              | abc  
| 1              | null  
| 2              | null
| 2              | null  
| 2              | null  
| 2              | abc  
| 2              | null
| 3              | null
| 3              | null  
| 3              | null  
| 3              | null  
| 3              | null

现在,当所有故障列数据的ID都为空时,我需要获取ID。

预期结果:

| id             | Failure            
+----------------+----------
| 3              | null
| 3              | null  
| 3              | null  
| 3              | null  
| 3              | null

2 个答案:

答案 0 :(得分:2)

如果只需要ID,请使用聚合:

select id
from t
group by id
having max(failure) is null;

我看不出获得所有重复行的理由。如果您需要它们,那么我建议not exists

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.id = t.id and t2.failure is not null
                 );

答案 1 :(得分:0)

    Select * 
    from Table 
    where Id not in (select id from Table where failure is not null)