我在db2的选择查询中有多行,它们在sum函数内使用带有AND的CASE。在mySQL上可以正常使用,但由于“与”而不再起作用。
我不能同时使用该关键字和case语句吗?我正在尝试将这些东西作为一个整体来汇总,而找不到IBM对此的直接解决方案。
原始查询:
select
sum(case when legtype1 = 2 then 1 else 0 end and answered = 1) as total_inbound
, sum(case when legtype1 = 2 then 1 else 0 end and answered = 0) as total_missed
, ROUND(COALESCE(100.00 * sum(case when legtype1 = 2 and answered = 1 then 1 end)/
sum(case when legtype1 = 2 then 1 end), 100),2) as percent_answered
from table1;
我尝试过
sum(case when legtype1 = 2 then 1 else 0 end, case when answered = 1 then 1 else 0 end)
但这也不正确。我需要根据两个条件都满足来进行求和,在DB2中我应该采用其他方法吗?我认为会有一种别名化每个条件的方法,但是我还没有找到任何东西。
答案 0 :(得分:1)
我认为DB / 2对其条件更为严格,不要让AND
和int
和条件,而应将结果作为SUM
的参数。本质上,这与AND
无关-如果您尝试对布尔值求和,例如,应该会遇到相同的问题。 SUM(answered = 1)
您应该能够在AND
表达式内推CASE
,像这样:
select
sum(case when legtype1 = 2 and answered = 1 then 1 else 0 end) as total_inbound
, sum(case when legtype1 = 2 and answered = 0 then 1 else 0 end) as total_missed
, ROUND(COALESCE(100.00 * sum(case when legtype1 = 2 and answered = 1 then 1 end)/
sum(case when legtype1 = 2 then 1 end), 100),2) as percent_answered
from table1;
答案 1 :(得分:0)
出于兴趣,您可以将Db2 11.1.2.2版中的BOOLEAN值相加
drop table table1;
create table table1(legtype1 int, answered int);
insert into table1 values (2,1),(2,1),(null, null),(2,0);
select
sum(legtype1 = 2 and answered = 1) as total_inbound
, sum(legtype1 = 2 and answered = 0) as total_missed
from table1;
TOTAL_INBOUND TOTAL_MISSED
------------- ------------
2 1