首页 > 解决方案 > db2 在 SUM 中使用带有 AND 的 CASE

问题描述

我在 db2 上的选择查询中有多行,它们在 sum 函数中使用带有 AND 的 CASE。这在 mySQL 上运行良好,但由于“AND”而不再有效。

我不能将该关键字与 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 中采用不同的方法吗?我认为有一种方法可以为每个条件加上别名,但我还没有找到任何东西。

标签: sqlsumdb2case

解决方案


我认为 DB/2 对其条件更严格,不让你AND使用intand 条件,并将结果视为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;

推荐阅读