我有两个数据库字段(SQL Server),这些字段是十进制的。在SQL查询中,这两个字段均为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]
答案 0 :(得分:4)
特殊情况吗?
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]
答案 1 :(得分:3)
在分母上使用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]
答案 2 :(得分:2)
您可以在使用这些值之前先进行检查。
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]
答案 3 :(得分:0)
用例...在计算之前..
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]
答案 4 :(得分:0)
选择TotalSalesPrice,CurrNewsPrice,CAST(CurrNewsPrice AS十进制(18,2))/ CAST(NULLIF(TotalSalesPrice,0)AS十进制(18,2))* 100.00 AS平均新闻 来自[dbo]。[N_NewsLine]
答案 5 :(得分:0)
如果您希望结果为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]