0

我正在尝试选择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

4 回答 4

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()数量。

于 2013-07-02T11:05:54.003 回答
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
于 2013-07-02T11:06:40.867 回答
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
于 2013-07-02T11:08:09.683 回答
0

如果 count 为 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
于 2013-07-02T11:11:57.153 回答