2011-09-08 188 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 
;