我如何克服 SQL 服务器错误 MSG 8134 除以零错误遇到的查询错误?

How do I get over a SQL Server error MSG 8134 Divide by zero error encountered Error in my query?

我正在尝试计算 2 列之间的百分比变化并遇到除以零错误错误。我想将所有 Null 显示为 0,但如果我使用 ISNULL,则会出现此错误。我该如何克服这个问题?

SELECT
   Table2014.OrderDate AS [December2014OrderDate],
   ISNULL(Table2014.Total, 0) AS [December2014DailySales],
   ISNULL(Table2013.Total, 0) AS [December2013DailySales],
   ISNULL(Table2014.Total, 0) - ISNULL(Table2013.Total, 0) AS [DailySalesDifference],
   100.0 * (ISNULL(Table2014.Total, 0) - ISNULL(Table2013.Total, 0)) / ISNULL(Table2013.Total, 0) AS [SalesDifferencePercentage],
   ISNULL(Table2013.OrderCount, 0) AS [December2013DailyOrderCount],
   ISNULL(Table2014.OrderCount, 0) AS [December2014DailyOrderCount],  
   ISNULL(Table2014.OrderCount, 0) - ISNULL(Table2013.OrderCount, 0) AS [DailyOrderCountDifference]
FROM 
   (SELECT
       SUM(order_header_total.oht_net) AS Total,
       DATEADD(DAY, 0, DATEDIFF(D, 0, order_header.oh_datetime)) AS OrderDate,
       COUNT(order_header.oh_id) AS OrderCount
    FROM 
       dbo.order_header_total
    INNER JOIN 
       dbo.order_header ON order_header_total.oht_oh_id = order_header.oh_id
    WHERE 
       order_header.oh_datetime BETWEEN '12/01/2014 00:00:00' AND '12/31/2014 23:59:59'
       AND order_header.oh_os_id IN (1, 6, 4)
       AND order_header.oh_cd_id = 76
    GROUP BY 
       DATEADD(DAY, 0, DATEDIFF(D, 0, order_header.oh_datetime))) Table2014
LEFT OUTER JOIN 
   (SELECT
        SUM(order_header_total.oht_net) AS Total,
        DATEADD(YEAR, 1, DATEADD(DAY, 0, DATEDIFF(D, 0, order_header.oh_datetime))) AS OrderDate,
        COUNT(order_header.oh_id) AS OrderCount
     FROM 
        dbo.order_header_total
     INNER JOIN 
        dbo.order_header ON order_header_total.oht_oh_id = order_header.oh_id
     WHERE 
        order_header.oh_datetime BETWEEN '12/01/2013 00:00:00' AND '12/31/2013 23:59:59'
        AND order_header.oh_os_id IN (1, 6, 4)
        AND order_header.oh_cd_id = 76
     GROUP BY 
        DATEADD(YEAR, 1, DATEADD(DAY, 0, DATEDIFF(D, 0, order_header.oh_datetime)))) Table2013 ON Table2013.OrderDate = Table2014.OrderDate
ORDER BY 
   Table2014.OrderD

而不是 Denominator 中的 Isnull 使用 NULLIF 来处理被零除错误。

select ...
100.0*Isnull((ISNULL(Table2014.Total,0) - ISNULL(Table2013.Total, 0)) / 
                  NULLIF(Table2013.Total, 0) AS [SalesDifferencePercentage],0),
 .....

NullIF 有助于将 denominator 中的 0 替换为 Null 这将避免提到的错误