SQL-总和然后除以零问题

时间:2018-10-19 10:22:19

标签: sql count rounding zero

我试图对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

2 个答案:

答案 0 :(得分:0)

我不确定如何将它们分组,但是我认为这是某种项目或ID?为了便于讨论,我已经将其称为ColumnID,但是您可以将其替换为实际使用的内容(例如InventoryItemName?)

然后您可以尝试执行此操作,它只检查未清数量是否为0。如果为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

答案 1 :(得分:0)

问题是您的子查询:

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 ;