sql - 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 中采用不同的方法吗?我认为有一种方法可以为每个条件加上别名,但我还没有找到任何东西。
解决方案
我认为 DB/2 对其条件更严格,不让你AND
使用int
and 条件,并将结果视为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;
推荐阅读
- php - Symfony5 JMS Serializer - 具有计算属性的模型,没有 ORM 注释
- list - 按元素值拆分列表
- javascript - 如何避免密码验证(JS)中的重复代码
- swift - WidgetKit 非协议类型的继承
- python - 生成欧拉砖
- javascript - 如何使用循环将正确的计数器值推送到 React 中的 HTML 元素?
- c - 您如何将以下代码转换为英特尔汇编代码 (x86)?
- mysql - 如何在 Codeigniter 中获得加入 3 个 MySql 表的不同结果?
- spring-kafka - Spring-kafka - 带有 AckMode Record 和自定义 SeekToCurrent 错误处理程序的消息丢失
- c# - 如何使用 iText7 和 C# 在 PDF 文件的标题中添加页码