如果没有记录或计数为零,则在DB2中返回“0”

rt4zxlrg  于 2022-11-07  发布在  DB2
关注(0)|答案(3)|浏览(153)

我尝试让这个工作查询返回0作为值,如果没有找到行并且count为0。
我已经尝试了IFNULL与一个零,coalesce和'then 1 else 0',但没有任何工作,我只是得到空白行。
在db2中查询:

select
   cust, 
   'PRIOR' as Range,
   coalesce(count(case when fordate between '2017-01-01' and '2017-04-13' then 1 
else 0 end),0)as count
from table1
where cust = 123
dl5txlt9

dl5txlt91#

对于COUNT调用的ELSE条件,您应该计算NULL,然后在计算中忽略它:

SELECT
    123 AS cust,
    'PRIOR' AS Range,
    COUNT(CASE WHEN fordate BETWEEN '2017-01-01' AND '2017-04-13' AND cust = 123
               THEN 1 END) AS count
FROM table1;

请注意,我省略了实际的ELSE条件,因为如果没有显式指定,默认值为NULL。此外,我将WHERE条件移到了条件计数中。这样做的效果是,即使该客户根本没有出现在表中,也始终返回一行。
选择cust看起来很奇怪,因为您要对整个表进行计数。

lawou6xi

lawou6xi2#

如果您的表中没有客户123的行,则需要“生成”这样一行。

SELECT
    c.cust, 
    'PRIOR' AS Range,
    (  SELECT COUNT(*) FROM table1 t
       WHERE t.cust = c.cust AND fordate BETWEEN '2017-01-01' AND '2017-04-13'
     ) AS count
FROM TABLE(VALUES( 123 )) AS c(cust)

或者可以使用LEFT OUTER JOIN

SELECT
    c.cust, 
    'PRIOR' AS Range,
    count(t.cust) AS count
FROM TABLE(VALUES( 123 )) AS c(cust)
LEFT OUTER JOIN table1 t
ON t.cust = c.cust
AND t.fordate BETWEEN '2017-01-01' AND '2017-04-13'
GROUP BY
   c.cust
hmtdttj4

hmtdttj43#

我有一个类似的问题,我想报告满足一个条件的行数。

SELECT Count(*), 'Duplicated Contractor LGA records - post-delete'  
FROM (SELECT Company, LGA 
      FROM   detcontractorLGA 
      GROUP BY Company, LGA 
      HAVING count(*) > 1 
     )
;

相关问题