简体   繁体   中英

Getting 'divide by zero' error when numerator, not denominator is 0

I have a 'Divide by 0' mystery in Redshift that is NOT coming from the denominator being 0.

I have two columns that are both decimals:Sales is always > 0, and it's my denominator. "Flagged Sales" is between 0 and up to the value of Sales.

When I run the code below (using Postico to query Redshift) I get the correct results, except that when "Flagged Sales"=0 I would like the result to be 0, not NULL.

 SELECT NULLIF("Flagged Sales") / NULLIF(Sales,0)::decimal AS "% of Sales Flagged" FROM Table1; 

The following attempts to get 0 when the numerator is 0 have resulted in the 'Divide by zero' error:

 CASE WHEN (NULLIF("Flagged Sales",0) / NULLIF(Sales,0)::decimal) IS NULL THEN 0 ELSE (NULLIF("Flagged Sales",0) / NULLIF(Sales,0)::decimal) END AS "% of Sales Flagged" 

Same with:

 COALESCE((NULLIF("Flagged Sales") / NULLIF(Sales,0)::decimal)) AS "% of Sales Flagged" 

Any ideas why this is happening?

This following code works fine for all combinations of Flagged Sales and Sales

select COALESCE(("Flagged Sales" / NULLIF(Sales,0)),0) AS "% of Sales Flagged"
from (select 0 as "Flagged Sales", 0 as Sales) as a
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM