如何解决被零除的问题?
我正在尝试计算利润百分比,但除以零误差。我是新来的,几乎所有论坛都尝试过,但是找不到任何解决方案。我正在使用SQL Server。
请帮助我,我在哪里犯错?
SELECT
SO_VInv.AccountNo, SUM(SO_VInv.LineCost) AS "Cost Price",
COUNT(SO_VInv.QuantityThisDel) AS Quantity, COUNT(SO_VInv.InvoiceNo) AS "Number of Invoices",
SUM(SO_VInv.CurrentLineTotal) AS "Sale Price", SUM(SO_VInv.CurrentLineTotal) - SUM(SO_VInv.LineCost) - SUM(SO_VInv.TaxToCharge) AS "Gross Profit",
SUM(SO_VInv.CurrentLineTotal) - SUM(SO_VInv.LineCost) - SUM(SO_VInv.TaxToCharge) / (SUM(SO_VInv.LineCost) - SUM(SO_VInv.TaxToCharge)
FROM
SO_VInv
WHERE
InvDate >= '2019-01-01'
GROUP BY
SO_VInv.AccountNo
以上行都工作正常,但是这部分引起了问题
SUM(SO_VInv.CurrentLineTotal) - SUM(SO_VInv.LineCost) - SUM(SO_VInv.TaxToCharge) / (SUM(SO_VInv.LineCost) - SUM(SO_VInv.TaxToCharge)
FROM
SO_VInv
WHERE
InvDate >= '2019-01-01'
GROUP BY
SO_VInv.AccountNo
我试图解决这样的问题,但仍然出现错误
DECLARE @SalePrice DECIMAL
DECLARE @Tax DECIMAL
DECLARE @CostPrice DECIMAL
DECLARE @Profit DECIMAL
DECLARE @Quantity DECIMAL
DECLARE @Final DECIMAL
SET @SalePrice = (SELECT(SUM(SO_VInv.CurrentLineTotal)) FROM SO_VInv )
SET @Tax = (SELECT(SUM(SO_VInv.TaxToCharge)) FROM SO_VInv )
SET @CostPrice = (SELECT(SUM(SO_VInv.LineCost)) FROM SO_VInv )
SET @Profit = (SELECT(@SalePrice-@Tax) FROM SO_VInv )
SET @Quantity = (SELECT COUNT(SO_VInv.QuantityThisDel)FROM SO_VInv )
SET @Final = (SELECT @SalePrice AS "SalePrice"
FROM SO_VInv
WHERE InvDate >= '2019-01-01'
GROUP BY SO_VInv.AccountNo)
SELECT @Final
除以零误差
我尝试了很多在线解决方案,包括声明和设置变量等方法。
答案 0 :(得分:2)
使用nullif()
:
select x / nullif(y, 0)
这将返回null
而不是生成错误。
对于您的特定声明:
SUM(SO_VInv.CurrentLineTotal) - SUM(SO_VInv.LineCost) - SUM(SO_VInv.TaxToCharge) / NULLIF(SUM(SO_VInv.LineCost) - SUM(SO_VInv.TaxToCharge), 0)
答案 1 :(得分:0)
您可以使用case语句,例如case的值等于零,然后为0,否则计算结束