我试图让这个工作查询返回0作为值,如果没有找到行且count为0。
我尝试过IFNULL一个零,合并和'然后1其他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
答案 0 :(得分:1)
对于ELSE
来电的COUNT
条件,您应该计算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
看看,因为你正在计算整个表格。我本来会做SELECT 123 AS cust, ...
,但如果DB2允许这种语法,那就这样吧。
答案 1 :(得分:1)
如果您的表没有客户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