SQL - 求和除以零问题

SQL - Sum then divide by zero problems

我正在尝试对 2 列求和并将一列除以另一列,但是在除以零时我遇到了问题。

数学本质上是 Sum(a)/Sum(b)

我的代码:

SELECT
      SUM(Inventory.QuantityOutstanding) as Quantity,   

      SUM(inventory.TotalValueOutstanding) as ExtValue,

      (SELECT NULLIF(sum(Inventory.TotalValueOutstanding), 0) /
      NULLIF(SUM(Inventory.QuantityOutstanding), 0)  FROM Inventory)  as AcctValue

FROM Inventory 
GROUP BY inventory.TotalValueOutstanding 

我的预期结果:

| Quantity | Extvalue  | AcctValue
|  -10.00  | -92.00    |  0.11
|   13.00  | 0.00      |  0
|   0.00   | 0.00      |  0
|   2.00   | 16.00     |  0.125

我的实际输出:

| Quantity | Extvalue  | AcctValue
|  -10.00  | -92.00    |  76.603066544004906470
|   13.00  | 0.00      |  76.603066544004906470
|   0.00   | 0.00      |  76.603066544004906470
|   2.00   | 16.00     |  76.603066544004906470

我不确定这些是如何分组的,但我会假设它是某种物品或 ID?为了争论起见,我将其称为 ColumnID,但您可以将其替换为您实际使用的内容(例如 InventoryItemName?)

然后您可以试试这个,它只检查未结数量是否为 0。如果是,则答案仅为 0,否则按正常方式计算公式。

SELECT
   Inventory.ColumnID,
   SUM(Inventory.QuantityOutstanding) as Quantity,   

   SUM(inventory.TotalValueOutstanding) as ExtValue,

   IIF(SUM(Inventory.QuantityOutstanding) = 0
        ,0
        ,isnull(sum(Inventory.TotalValueOutstanding), 0) /
           sum(Inventory.QuantityOutstanding)
       ) as AcctValue
FROM 
   Inventory 
GROUP BY
   Inventory.ColumnID

问题出在您的子查询上:

SELECT SUM(i.QuantityOutstanding) as Quantity,   
       SUM(i.TotalValueOutstanding) as ExtValue,
       (NULLIF(SUM(i.TotalValueOutstanding), 0) /
               NULLIF(SUM(i.QuantityOutstanding), 0)
       ) as AcctValue
FROM Inventory i
GROUP BY i.TotalValueOutstanding ;

我发现双 NULLIF() 有点令人困惑。使用 CASE:

可能会更清楚
SELECT SUM(i.QuantityOutstanding) as Quantity,   
       SUM(i.TotalValueOutstanding) as ExtValue,
       (CASE WHEN SUM(i.QuantityOutstanding) = 0 THEN 0
             ELSE SUM(i.TotalValueOutstanding) /                   
                  SUM(i.QuantityOutstanding)
        END) as AcctValue
FROM Inventory i
GROUP BY i.TotalValueOutstanding ;