我在下面有以下一段sql。第二行(已注释掉)包含我添加的检查以查看如果计算返回负值,在这种情况下它应该选择NULL 。这种情况属于多个其他案例陈述的块内。由于我的方法意味着两次运行相同的计算,如果此计算列的值为负值,而不是进行两次类似的计算,那么选择NULL会有更好的替代方法或更有效的方法吗?
由于
CASE
WHEN M.ALPHA = 'B' OR T.CT IN (0.001, 0.002) THEN NULL
-- WHEN ((M.VAL / NULLIF (M.VAL2, 0)) / (NULLIF (T.VAL, 0) / T.VAL2)) < 0 THEN NULL
ELSE (M.VAL / NULLIF (M.VAL2, 0)) / (NULLIF (T.VAL, 0) / T.VAL2)
END As WORLD
答案 0 :(得分:0)
您可以将计算移动到子查询。例如:
select case
when CalculatedColumn > 42 then 'Hot'
when CalculatedColumn < 42 then 'Cold'
else 'Answer'
end as Description
from (
select 2 * col1 + 3 as CalculatedColumn
from YourTable
) SubQuery
有时在with
子句中定义子查询更清楚:
; with SubQuery as
(
select 2 * col1 + 3 as CalculatedColumn
from YourTable
) SubQuery
select case
when CalculatedColumn > 42 then 'Hot'
when CalculatedColumn < 42 then 'Cold'
else 'Answer'
end as Description
from SubQuery