用于获取表中3个值的计数的SQL查询

时间:2018-05-04 19:30:05

标签: sql

我正在寻找一个直接选择查询来获取以下条件的计数,而不是在我的pl / sql存储过程中使用if else条件。

if (A > 0 & B > 0 & C >0){

    return count=3

} else if (A <0 & B<0 & C >0 || A<0 & B>0 & C<0 || A >0 & B <0 & C <0 ) 
{ 

    return count = 1

} else if (A>0 & B>0 & C <0 || A>0 & B<0 & C>0 || A <0 & B >0 & C >0 ) 
{ 

    return count = 2

} else (A<0 & B<0 & C <0){

    return count = 0
}

2 个答案:

答案 0 :(得分:1)

嗯。如果我正确地遵循逻辑,我会这样做:

select ( (case when A > 0 then 1 else 0 end) +
         (case when B > 0 then 1 else 0 end) +
         (case when C > 0 then 1 else 0 end)
       ) as cnt
from t;

答案 1 :(得分:0)

你可以在

时使用案例
  select case when   (A > 0 AND  B > 0 AND C >0) THEN 3 
    when ( (A <0 AND  B<0 AND  C >0 ) OR ( A<0 AND B>0 AND C<0) OR  (A >0 AND B <0 AND C <0 )) THEN 1 
    when ( (A >0 AND  B>0 AND  C<0 ) OR ( A>0 AND B<0 AND C>0) OR  (A <0 AND B >0 AND C >0 )) THEN 2
              ELSE 0 
          END as my_result

  from my_table