将 Null 除以 SQL 中的数字

Divide Null by a number in SQL

我有一个问题:如果我在 SQL 中有一个 Product table,其中包含列 Product IDTotalPriceNumberOfUnits

现在我需要计算产品的unitPrice

这可以通过 TotalPrice 除以 NumberOfUnits 来计算。

现在的问题是:如果 totalPriceNull 并且 NumberOfUnits 是 45.

输出结果是什么?

Select 
    ProductID,
    (TotalPrice / NumberOfUnits) as UnitPrice 
from ProductTable

输出结果是什么?

如果答案为空,我们该如何处理?

我会去:

Select ProductID
,(isnull(TotalPrice, 0)/NumberOfUnits) as UnitPrice
from ProductTable

在这种情况下,isnull(totalPrice, 0) 将任何 NULL 值替换为 0

  1. Null/45 = NULL
  2. anynumber/null = 空

您的 table 结构不正确,您需要以一种不接受价格和数量为空的方式创建 table。

休息会有大讨论:)

空 = NULL。

SELECT NULL / 45

结果

Column1
NULL

处理将是...

SELECT IsNull(NULL, 0) / 45

结果

Column1
0