字段  aa   bb
      1    1
      0    0
      0    1
      0    0 
要求实现:如果bb的值=1 ,加入条件查询aa=1的数据如果bb的值=0,不加入查询aa的条件 

解决方案 »

  1.   

    select * from 
    bb = 1 and aa = 1
    or bb = 0
      

  2.   

    结果是不是要
    aa   bb
          1    1
          0    0
          0    0 
      

  3.   

    我的意思是,如果BB=0就不用理AA了
      

  4.   

    字段  aa   bb  cc
          1    1  李小姐
          0    0  张小姐
          0    1  陈小姐
          0    0  易小姐
    这样问如果bb=1 那么就输出 aa=1的值哪果BB=0 那么就输出 所有的值
      

  5.   

    select
       case bb when 1 then (select aa from tb where aa=1) 
               when 0 then ...end
    from
       tb
      

  6.   


    select * from table1
    where bb = 1 and aa = 1
    union all
    select * from table1
    where  bb = 0
      

  7.   


    消息 156,级别 15,状态 1,第 3 行
    关键字 'end' 附近有语法错误。
      

  8.   

    --错了修改
    begin
    if(bb=1)
    select * from tb where aa=1
    else
    select * from tb
    end
      

  9.   

    select * 
    from tb1
    where (case when bb=1 then aa else 1 end)=1
      

  10.   

    declare @bb2 int
    set @bb2=1
    --set @bb2=0select *  
    from tb1
    where (case when @bb2=1 then aa else 1 end)=1
      

  11.   


    where (
             (bb = 1 and aa = 1) or
             (bb <> 1)
          )
      

  12.   


    if object_id('test') is not null
    drop table test
    gocreate table test(aa int, bb int, cc nvarchar(5))
    goinsert into test
    select 1, 1, '李小姐' union all
    select 0, 0, '张小姐' union all
    select 0, 1, '陈小姐' union all
    select 0, 0, '易小姐'
    goselect *
    from test 
    where bb = 1 and aa =1 or bb =0
    goif object_id('test') is not null
    drop table test
    go/*
    aa          bb          cc
    ----------- ----------- -----
    1           1           李小姐
    0           0           张小姐
    0           0           易小姐
    */
      

  13.   


    where (bb=1 and aa =1) or bb=0
      

  14.   

    if object_id('test') is not null
        drop table test
    create table test(aa int, bb int, cc nvarchar(5))
    go
    insert into test
    select 1, 1, '李小姐' union all
    select 0, 0, '张小姐' union all
    select 0, 1, '陈小姐' union all
    select 0, 0, '易小姐'
    go
    --SQL:
    select * from test
    where aa = (case when bb = 1 then 1 else aa end)
    /*
    aa bb cc
    1 1 李小姐
    0 0 张小姐
    0 0 易小姐
    */