2011-09-08 121 views
2

我有一个详细表 “详细信息”,这是象下面这样:根据条件选择一个列?

详细信息:

ID   StatusID 
    ----   -------- 
    1    4 
    1    4 
    2    4 
    2    3 
    3    4 
    3    4 
    4    3 
    4    3 

在这里,我想只选择其中包含所有StatusID = 4 ID:

我期望的结果应如下所示:

ID 
---- 
    1 
    3 

如何实现此目的?

回答

2

你可以使用一个子查询not exists

select distinct yt1.ID 
from YourTable yt1 
where yt1.StatusID = 4 
     and not exists 
     (
     select * 
     from YourTable yt2 
     where yt2.StatusID <> 4 
       and yt2.ID = yt1.ID 
     ) 
+0

谢谢你这么多... – thevan

1
select distinct ID 
from YourTable 
where ID not in 
(
    select ID 
    from YourTable 
    where StatusID <> 4 
) 
1

只是为了好玩,怎么样加入版本

select distinct 
     t.id 
    from 
     your_table as t 
     left outer join(select 
       id, 
       statusid 
      from 
       your_table 
      where 
       statusid != 4 
     ) as j 
      on t.id = j.id 
    where 
     j.id is null 
;