[英]Take Avg value as a 0 when Divide it by zero
我有两个数据库字段(SQL Server),这些字段是十进制的。 SQL Query中的这两个字段都是0我需要占用这些值的百分比。 在此记录中显示数据库错误。 但如果发生这种情况,我需要显示0值。
有一个场景TotalSalesPrice = 0.00&CurrNewsPrice = 0然后Avgnews公式是AvgNews =(CurrNewsPrice / TotalSalesPrice)* 100
Select TotalSalesPrice,CurrNewsPrice,CAST(CurrNewsPrice AS decimal(18,2)) / CAST(TotalSalesPrice AS decimal(18,2)) * 100.00 AS AvgNews
from [dbo].[N_NewsLine]
特例呢?
select TotalSalesPrice,CurrNewsPrice, case
when TotalSalesPrice = 0 and CurrNewsPrice = 0 then 0
else CAST(CurrNewsPrice AS decimal(18,2)) /
CAST(TotalSalesPrice AS decimal(18,2)) * 100.00
end AS AvgNews
from [dbo].[N_NewsLine]
在分母上使用NULLIF()
。 和ISNULL()
的计算结果
Select TotalSalesPrice,
CurrNewsPrice,
ISNULL(CAST(CurrNewsPrice AS decimal(18,2))
/ CAST(NULLIF(TotalSalesPrice, 0) AS decimal(18,2)) * 100.00, 0) AS AvgNews
from [dbo].[N_NewsLine]
您可以在使用这些值之前进行检查。
Select TotalSalesPrice,CurrNewsPrice,IIF(TotalSalesPrice = 0,
0,
CAST(CurrNewsPrice AS decimal(18,2)) / CAST(TotalSalesPrice AS decimal(18,2)) * 100.00) AS AvgNews
from [dbo].[N_NewsLine]
用例...当...计算之前
Select TotalSalesPrice,CurrNewsPrice,
CAST( Case CAST(TotalSalesPrice AS decimal(18,2))
when 0 then 0.00
else CAST(CurrNewsPrice AS decimal(18,2)) / CAST(TotalSalesPrice AS decimal(18,2)) * 100.00 end AS decimal(18,2)) AS AvgNews
from [dbo].[N_NewsLine]
选择TotalSalesPrice,CurrNewsPrice,CAST(CurrNewsPrice AS decimal(18,2))/ CAST(NULLIF(TotalSalesPrice,0)AS decimal(18,2))* 100.00 AS AvgNews来自[dbo]。[N_NewsLine]
如果您希望结果为decimal(18, 2)
则在除法后执行cast()
。 分割小数时的结果类型的规则是。 。 。 而拜占庭(没有针对拜占庭人的罪行)。
我建议使用NULLIF()
来避免被零除,从而导致:
Select TotalSalesPrice, CurrNewsPrice,
cast(CurrNewsPrice * 100.00 /
nullif(TotalSalesPrice, 0) as decimal(18, 2)
) as AvgNews
from [dbo].[N_NewsLine]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.