选择查询返回值0表示不满足条件

时间:2013-07-02 11:01:42

标签: mysql

我正在尝试选择count(*)作为某个变量,并根据某些条件按产品分组。

如果不满足该条件,我希望查询为该产品的count变量值返回0。

我正在使用MySQL数据库并试图在SAS中使用它,这是我的查询:

  SELECT COUNT(*) AS common_mtrl, product AS product2 
    FROM join_mkt_sort A, support_mtrl B  
   WHERE support_mtrl_ind >= 1
         AND A.EKEY = B.SKEY 
         AND A.PKEY = B.SKEY
GROUP BY product

我希望查询为不符合条件的产品分配0到变量common_mtrl

4 个答案:

答案 0 :(得分:2)

问题是你的加入。假设您想要的所有行都在“A”表中,您可以像这样加入它们:

select count(B.SKEY) as common_mtrl, product as product2
from join_mkt_sort A left outer join
     support_mtrl B  
     on A.EKEY = B.SKEY and A.PKEY = B.SKEY and
        support_mtrl_ind >=1 
group by product;

即使没有匹配项,left outer join也会保留第一个表中的所有行。 count()计算匹配数。

答案 1 :(得分:0)

select sum(case when support_mtrl_ind >=1 then 1 else 0 end) as common_mtrl,
       product as product2 
from join_mkt_sort A
    ,support_mtrl B  
where A.EKEY = B.SKEY and A.PKEY = B.SKEY
group by product

答案 2 :(得分:0)

SELECT COALESCE(COUNT(b.skey),0) common_mtrl
     , product product2 
  FROM join_mkt_sort A
  LEFT
  JOIN support_mtrl B  
    ON A.EKEY = B.SKEY 
   AND A.PKEY = B.SKEY
   AND support_mtrl_ind >= 1 -- not sure which table this comes from
 GROUP 
    BY product

答案 3 :(得分:0)

检查条件是否为0

 set @count int=0 set @result int select @count=count(*) as
 common_mtrl,product as product2 from join_mkt_sort A,support_mtrl B  
            where support_mtrl_ind >=1 
            and A.EKEY = B.SKEY and A.PKEY = B.SKEY
            group by product if(@count=0) set @result=0