sql - case语句的顺序

时间:2017-04-25 12:35:57

标签: sql

有以下代码:

select a,b,c,d
case when a > 5 or a < 2 then null end as a
case when a is null then null when a = 0 then b else b/a end as e
from table

实际上我想要排除每一行&gt; 5或者&lt; 2,然后只执行计算。上述代码在第二种情况下失败,因为它不考虑第一种情况

1 个答案:

答案 0 :(得分:1)

  

实际上我想要排除每一行&gt; 5或者&lt; 2,   然后只对它进行计算。

您不会使用case过滤行。您使用where过滤行:

select a, b, c, d,
       (case when a = 0 then b else b/a end) as e
from table
where a >= 2 and a <= 5;

当然,考虑到你的约束,a不能为0,所以case是多余的。

如果您只想要所有行但计算a的某些值,请简化为:

select a, b, c, d,
       (case when a >= 2 and a <= 5 then b/a end) as e
from table;