Sql db2用例中包含和和
我在db2上的select查询中有多行代码,它们与sum函数一起使用,并在sum函数内部使用。这在mySQL上运行得很好,但由于“和”的原因,不再有效 我不能在案例陈述中使用该关键字吗?我试图将这些东西聚合为一个整体,但找不到IBM的直接解决方案 原始查询:Sql db2用例中包含和和,sql,sum,db2,case,Sql,Sum,Db2,Case,我在db2上的select查询中有多行代码,它们与sum函数一起使用,并在sum函数内部使用。这在mySQL上运行得很好,但由于“和”的原因,不再有效 我不能在案例陈述中使用该关键字吗?我试图将这些东西聚合为一个整体,但找不到IBM的直接解决方案 原始查询: select sum(case when legtype1 = 2 then 1 else 0 end and answered = 1) as total_inbound , sum(case when legtype
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中有不同的方法吗?我认为有一种方法可以对每个条件进行别名,但我还没有找到任何东西。我认为DB/2对其条件更加严格,不允许使用
和一个int
和一个条件,并将结果视为SUM
的参数。本质上,这与和
无关-如果尝试对布尔值求和,您应该会看到相同的问题,例如SUM(responsed=1)
您应该能够将和
推送到案例
表达式中,如下所示:
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;
出于兴趣,您可以对DB211.1.2.2中的布尔值求和
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
看起来是这样,明白了,谢谢!我甚至都没想过要试试