我知道Redshift中的浮点周围有一些陷阱,但我无法克服。
我有col1和col2列,并想创建一个简单的除法为“ calc”。col1和col2有时为零,因此我在col2> 0的地方使用。col1和col2没有空值。这很好用:
select col1*1.0/col2 as calc
from t1
where col1 > 0 and col2 > 0
但是,如果我在where子句中为calc使用任何值,则会收到错误消息:
select calc from
(select col1*1.0/col2 as calc
from t1
where col1 > 0 and col2 > 0)
where calc < 1 -- error here for any value, gt or lt
SQL Error [500310] [57014]: [Amazon](500310) Invalid operation: Divide by zero;
我尝试了很多事情,包括calc的不同值,转换为十进制或浮点数,但是却遇到了相同的错误。为什么?
Redshift可能以一种导致select
子句中的除法在子句中的条件之前被求值的方式优化查询的操作树where
。
您可以使用以下方法解决此问题nullif()
:
select calc
from (
select col1 * 1.0 / nullif(col2, 0) as calc
from t1
where col1 > 0 and col2 > 0
)
where calc < 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句