Redshift - 除以零错误

Redshift - Divide by zero error

我遇到以下问题,不断抛出 "Divide by zero" 错误

下面是我正在使用的查询:

select cust_name,
sum(case WHEN sale_date > CURRENT_TIMESTAMP-14 AND sale_date < CURRENT_TIMESTAMP then 1 else 0  END) AS "0_2_sales_count",
sum(case WHEN sale_date > CURRENT_TIMESTAMP-28 AND sale_date < CURRENT_TIMESTAMP-14  then 1 else 0  END) AS "2_4_sales_count",
("0_2_sales_count") - ("2_4_sales_count") as "load_volume_diff_0_2_2_4",
(("0_2_sales_count" - "2_4_weeks_load_volume")/"2_4_sales_count"::float) * 100  as "load_volume_diff_percent_0_2_2_4"
from sales 
group by cust_name;

我在“0_2_sales_count”和“2_4_sales_count”列中为不同的客户设置了零。谁能建议我如何处理上述错误。我已经尝试使用 case when column = 0 但仍然出现同样的问题。

我正在使用 Amazon Redshift 数据库。

谢谢

您可以使用大小写检查“2_4_sales_count”中的 0,并针对每种情况使用正确的代码

select cust_name,
      sum(case WHEN sale_date > CURRENT_TIMESTAMP-14 
          AND sale_date < CURRENT_TIMESTAMP then 1 else 0  END) AS "0_2_sales_count",
        sum(case WHEN sale_date > CURRENT_TIMESTAMP-28 
          AND sale_date < CURRENT_TIMESTAMP-14  then 1 else 0  END) AS "2_4_sales_count",
      ("0_2_sales_count") - ("2_4_sales_count") as "load_volume_diff_0_2_2_4",
      CASE WHEN "2_4_sales_count"::float = 0
          THEN 0 ELSE (("0_2_sales_count" - "2_4_weeks_load_volume")/"2_4_sales_count"::float) * 100  END as "load_volume_diff_percent_0_2_2_4"
from sales 
group by cust_name;

尝试使用 case when like case when "2_4_sales_count"::float =0 then 1 end

select cust_name,
sum(case WHEN sale_date > CURRENT_TIMESTAMP-14 AND sale_date < CURRENT_TIMESTAMP then 1 else 0  END) AS "0_2_sales_count",
sum(case WHEN sale_date > CURRENT_TIMESTAMP-28 AND sale_date < CURRENT_TIMESTAMP-14  then 1 else 0  END) AS "2_4_sales_count",
("0_2_sales_count") - ("2_4_sales_count") as "load_volume_diff_0_2_2_4",
(("0_2_sales_count" - "2_4_weeks_load_volume")/case when "2_4_sales_count"::float =0 then 1 end) * 100  as "load_volume_diff_percent_0_2_2_4"
from sales 
group by cust_name;

据推测,问题出在这一行:

(("0_2_sales_count" -"2_4_weeks_load_volume") / "2_4_sales_count"::float) * 100  as "load_volume_diff_percent_0_2_2_4"

我会这样写:

(("0_2_sales_count" - "2_4_weeks_load_volume") * 100.0 / nullif("2_4_sales_count", 0.0) as "load_volume_diff_percent_0_2_2_4"

除以零的最简单解决方案是 nullif()