我遇到以下问题,并不断抛出“被零除”错误
以下是我正在使用的查询:
-1
我在“ 0_2_sales_count”和“ 2_4_sales_count”列中为不同的客户设置了零。任何人都可以建议我该如何处理以上错误。我尝试使用column = 0但仍然出现相同问题的情况。
我正在使用Amazon Redshift DB。
谢谢
答案 0 :(得分:1)
您可以使用大小写检查“ 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;
答案 1 :(得分:1)
尝试使用“ 2_4_sales_count” :: float = 0然后1结尾的情况
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;
答案 2 :(得分:0)
大概是此行中的问题:
(("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()
。