Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Divide By Zero Error In SELECT Statement

I'm brand new to SQL and could use a hand. I'm getting a divide by zero error with the following in my SELECT statement:

SUM(Cast((replace(replace(replace (p.[Total Sales], '$', ''), '(','-'),  ')','')) as money)) - SUM(Cast((replace(replace(replace (p.[Total Cost], '$', ''), '(','-'),  ')','')) as money)) / SUM(Cast((replace(replace(replace (p.[Total Sales], '$', ''), '(','-'),  ')','')) as money)) as new_bal

I know that I need to use CASE, but I'm not sure of the application.

like image 872
E. Peterson Avatar asked Jul 05 '26 18:07

E. Peterson


1 Answers

You could use NULLIF in following:

NULLIF(expression1, 0)

In your case It will be:

SUM(Cast((replace(replace(replace (p.[Total Sales], '$', ''), '(','-'),  ')','')) as money)) - SUM(Cast((replace(replace(replace (p.[Total Cost], '$', ''), '(','-'),  ')','')) as money)) / NULLIF(SUM(Cast((replace(replace(replace (p.[Total Sales], '$', ''), '(','-'),  ')','')) as money)),0) as new_bal
like image 140
Stanislovas Kalašnikovas Avatar answered Jul 07 '26 08:07

Stanislovas Kalašnikovas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!