如何在 SQL 中以最有效的方式应用嵌套 case when 语句?

How to apply nested case when statements in the most efficient way possible in SQL?

我正在尝试从具有三个 table 的连接中 select 两列。具体来说,第一列是一个比率,如果另一列等于 1,则计算为两列之间的减法。第二列是一个标志,表示 txn_rate 不为空的次数。我是否以最有效的方式执行 'case when' 语句?请看下面的代码(我屏蔽了连接逻辑以使其更简单,因为我认为这不太重要)

一个简短的说明:我想遵循的逻辑是创建一个标志,然后在分段 table 中对标志求和(这是预分段)。有没有更有效的方法来创建二进制标志?

Select case when a.column = 1 then (b.column - c.column) else null end as txn_rate,
       case when (case when a.column = 1 then (b.column - c.column) else null end) is not null then 1 
       else null end as txn_rate_flag

FROM table1 a

Left Join table2 b
ON a.ID = b.ID
Left Join table3 c
ON a.ID2 = c.ID2

如果您只想对标志求和,则将条件 a.column = 1 移动到 WHERE 子句并检查 b.column - c.column 是否为 NULL(它可以在 LEFT JOIN) 在 CASE 表达式中:

SELECT 
  SUM(CASE WHEN (b.column - c.column) IS NOT NULL THEN 1 ELSE 0 END) AS total_flags
FROM table1 a
LEFT JOIN table2 b ON a.ID = b.ID
LEFT JOIN table3 c ON a.ID2 = c.ID2
WHERE a.column = 1

我会写以下内容


    case when (case when a.column = 1 then (b.column - c.column) else null end) is not null then 1 
           else null end as txn_rate_flag

作为case when a.column = 1 and (b.column - c.column) is not null then 1 else null as txn_rate_flag