根据条件选择一个列?

时间:2011-09-08 11:23:54

标签: sql sql-server sql-server-2005 select where

我有一个详细信息表“详细信息”,如下所示:

详情:

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

在这里,我想只选择具有所有StatusID = 4的ID:

我想要的结果应如下所示:

  ID
 ----
  1
  3

如何实现这一目标?

3 个答案:

答案 0 :(得分: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
        )

答案 1 :(得分:1)

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

答案 2 :(得分: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
;