查询以检索所有相关值都为null的组

  • 本文关键字:null 的组 检索 查询 sql
  • 更新时间 :
  • 英文 :


我有以下内容:

| Group_ID | Value |
|----------|-------|
|      146 |  A    |
|      146 |  B    |
|      239 |  NULL |
|      239 |  F    |
|      826 |  NULL |
|      826 |  NULL |


我只需要检索所有相关值为null的ID。在本例中,输出为826

我知道这似乎是一个简单的问题,但我已经为此挣扎了很长时间。

select group_id 
from t
group by group_id having sum(case when value is null then 1 end)=count(*)

这应该做到:

select t1.group_id
from foo t1
group by t1.group_id
having count(*) = (select count(*) 
                   from foo t2 
                   where t2.group_id = t1.group_id
                     and t2.value is null);

SQLFiddle示例:http://sqlfiddle.com/#!15/7d228/1

SELECT  DISTINCT Group_ID
FROM    Your_Table a
WHERE   Value IS NULL
   AND  NOT EXISTS (
                     SELECT   NULL
                     FROM     Your_Table b
                     WHERE    Value IS NOT NULL
                         AND  b.Group_ID = a.Group_ID
                   )

试试这个:

select distinct Group_id 
from test 
where value is null 
   and Group_id not in (select Group_id from test where value is not null)

最新更新