如何在SQL中以最有效的方式使用嵌套大小写?

问题描述 投票:-2回答:2

我正在尝试从具有三个表的联接中选择两列。具体来说,第一列是一个速率,如果另一列等于1,则计算为两列之间的减法。第二列是txn_rate不为空的次数的标志。我是否以最有效的方式进行“案件何时”陈述?请参见下面的代码(我掩盖了连接逻辑,使其更简单,因为我认为这不太重要)

快速说明:我要遵循的逻辑是创建一个标志,然后将该标志加到暂存表中(这是预暂存)。有没有更有效的方法来创建二进制标志?

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

sql sql-server-2008 case-when
2个回答
0
投票

如果您只想对标志求和,然后将条件a.column = 1移至WHERE子句,然后检查b.column - c.column是否为NULL(在LEFT JOIN中可能)在[ C0]表达式:

CASE

0
投票

我会写以下内容

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

© www.soinside.com 2019 - 2024. All rights reserved.