SQL语句中的SQL除以零错误

E. *_*son 3 mysql sql case divide-by-zero

我是SQL的新手,可以用手.我在SELECT语句中得到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

我知道我需要使用CASE,但我不确定应用程序.

Sta*_*vas 5

你可以在下面使用NULLIF:

NULLIF(expression1, 0)

在你的情况下它将是:

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
Run Code Online (Sandbox Code Playgroud)

  • @DanField...你将`NULLIF()`函数与其他东西混淆了.它返回"NULL"而不是"归零".注意:`NULLIF()`是ANSI标准函数,在大多数数据库中都可用.这是我防止此类错误的首选方法. (4认同)