为什么 Redshift 给我除以零的错误?
why is Redshift giving me a divide by zero error?
我知道 Redshift 中的浮点数存在一些陷阱,但我无法克服这个问题。
我有列 col1 和 col2,想创建一个简单的除法作为“calc”。 col1 和 col2 有时为零,因此我使用 where col2 > 0。col1 和 col2 没有空值。这很好用:
select col1*1.0/col2 as calc
from t1
where col1 > 0 and col2 > 0
但是如果我在 calc 的 where 子句中使用任何值,我会得到错误:
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
我知道 Redshift 中的浮点数存在一些陷阱,但我无法克服这个问题。
我有列 col1 和 col2,想创建一个简单的除法作为“calc”。 col1 和 col2 有时为零,因此我使用 where col2 > 0。col1 和 col2 没有空值。这很好用:
select col1*1.0/col2 as calc
from t1
where col1 > 0 and col2 > 0
但是如果我在 calc 的 where 子句中使用任何值,我会得到错误:
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