现在一张表,字段如下
    ID ANAME ATJ AVALUE
1 a 1 11
2 b -1 -11
3 c 0 100
4 d 1 111
如果atj=1则执行id>1
如果atj=-1则执行id<3
如果atj=0则执行(id>1 or id<3)
下面我做的是不对的,请问高手门如何实现
select case when atj=1 then id>1
       case when atj=-1 then id<3
       case when atj=0 then (id>1 or id<3)
       from aaa

解决方案 »

  1.   

    意思是字段atj=1时,执行select * from aaa where id>1
    字段atj=-1时,执行select * from aaa where id<3
    字段atj=0时,执行select * from aaa where id>1 or id<3
      

  2.   

    不知道,好像不行 你看用这种行吗?试试看!~~ (ATJ为表名,其他的一样)  select a.*
        from ATJ a
       where a.atj = 1
         and a.id > 1
      union 
        select a.*
          from ATJ a
       where a.atj = -1
         and a.id < 3
      union
        select a.*
          from ATJ a
       where a.atj = 0
         and a.id > 1
         and a.id < 3;
    结果:---------------------------------        ID ANAME        ATJ     AVALUE
    ---------- ----- ---------- ----------
             2 b             -1        -11
             4 d              1        111
      

  3.   

    就是说,如果传过来的值=1时,执行select * from  aaa where id>1
    结果应该是这样的
    2 b -1 -11
    3 c 0 100
    4 d 1 111
      

  4.   

    SELECT * FROM AAA WHERE (atj=1 AND id>1) OR
    (atj=-1 AND id<3) OR (atj=0 AND (id>1 or id<3))
      

  5.   

    楼上的不是我的要意思
    我是想接收一个参数,参数值=1时,执行select * from  aaa where id>1
    参数值=-1时,执行select * from  aaa where  id<3
    参数值=0时,执行select * from  aaa where  id>1 or id<3
      

  6.   

    参数值=1时即 atj=1时,执行select * from aaa where id>1,我查出来是3条
    结果应该是这样的2   b  -1    -11
    3  c  0    100
    4   d  1    111
      

  7.   

    把判断逻辑写在程序里. 或在存储过程中用动态SQL出数据也会方便很多.
      

  8.   

    SELECT *
      FROM aaa
     where (id>1 or (:atj<>1)) 
       and (id<3 or (:atj<>-1))
       and ((id>1 or id<3) or (:atj<>0))
       --atj为参数
      

  9.   

    我觉得楼上的不对,应该这么写才好(请楼主试一下)
    select * from aaa
    where (id>1 and :atj=1)
    or (id<3 and :atj=-1)
    or ((id >1 or id <3) and :atj=0);
      

  10.   

    我觉得逻辑有点问题吧,id>1 or id<3 即是全集了,就相当于不加条件,是否应该改成:
    select * from aaa
    where (id>1 and :atj=1)
    or (id<3 and :atj=-1)
    or ((id >1 and id <3) and :atj=0);
      

  11.   

    是的,(id >1 or id <3) 是我不小心打错了,应该用and