【问题标题】:Select a Column based on Condition?根据条件选择列?
【发布时间】:2011-11-12 22:04:55
【问题描述】:

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

详情:

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

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

我想要的结果应该如下:

  ID
 ----
  1
  3

如何做到这一点?

【问题讨论】:

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


    【解决方案1】:

    您可以使用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
            )
    

    【讨论】:

      【解决方案2】:
      select distinct ID 
      from YourTable
      where ID not in
      (
          select ID 
          from YourTable
          where StatusID <> 4
      )
      

      【讨论】:

        【解决方案3】:

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

        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
        ;
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-01
          • 1970-01-01
          • 2016-11-02
          • 2013-12-27
          • 2016-09-16
          • 2013-06-02
          相关资源
          最近更新 更多