2015-01-07 117 views
0

我有這個SQL語句,除了OrderCountPercentage計算以外工作正常。我不明白爲什麼它不計算這些公式是正確的。我只能認爲它與使用COUNT函數的事實有關。任何幫助讚賞。SQL Server百分比計算沒有正確計算

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, 
     (ISNULL(Table2014.Total, 0) - ISNULL(Table2013.Total, 0))/NULLIF(Table2013.Total, 0) * 100  AS SalesPercentage, 
     ISNULL(Table2014.OrderCount, 0)                 AS December2014DailyOrderCount, 
     ISNULL(Table2013.OrderCount, 0)                 AS December2013DailyOrderCount, 
     ISNULL(Table2014.OrderCount, 0) - ISNULL(Table2013.OrderCount, 0)         AS DailyOrderCountDifference, 
     (ISNULL(Table2014.OrderCount, 0) - ISNULL(Table2013.OrderCount, 0))/Table2013.OrderCount * 100 AS Percentage 
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_order_number)      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_order_number)           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.OrderDate 

回答

0

問題可能是整數除法。我想你是指:

(ISNULL(Table2014.OrderCount, 0) - ISNULL(Table2013.OrderCount, 0))/Table2013.OrderCount * 100 AS Percentage 

如果所有這些都是整數,除法是一個整數。我通常通過乘以1.0來解決這個問題。但也許更正式的方法是將其中一個值轉換爲浮點或數值:

(ISNULL(Table2014.OrderCount, 0) - ISNULL(Table2013.OrderCount, 0))/cast(Table2013.OrderCount as float) * 100 AS Percentage 
+0

完美,工作! – TowelsRus