SQL GROUP BY语句csv导出显示不正确的总和

时间:2018-07-03 06:56:57

标签: sql sql-server database csv

在SQL Server 2012中运行查询并通过将结果另存为选项在csv中导出成本记录,查询如下所示:

SELECT 
    ...,...,...,...,...,......,...,..,..,
    SUM(COST_REPORTING.Actual_Cost) AS Actual_Cost
FROM 
    Table_Name AS Table_Name 
WHERE 
    USAGESTARTDATE >='2018-05-01 00:00:00.000'  
    AND USAGEENDDATE<='2018-05-31 12:00:00.000'
GROUP BY 
    ...,...,...,...,...,......,...,..,..,

csv中所有Actual_Cost记录的总和显示1817751.612

但是,如果我只是将Actual_Cost列另存为csv,则在检查所有成本记录的SUM为1823065.094时,结果如下:

SELECT
    Z.Actual_Cost 
FROM
    (SELECT 
         ...,...,...,...,...,......,...,..,..,
         SUM(COST_REPORTING.Actual_Cost) AS Actual_Cost
     FROM 
         Table_Name AS Table_Name 
     WHERE 
         USAGESTARTDATE >='2018-05-01 00:00:00.000' 
         AND USAGEENDDATE<='2018-05-31 12:00:00.000'
     GROUP BY ...,...,...,...,...,......,...,..,..,) AS Z

我还使用SQL查询检查了所有ACTUAL_COST记录的总和,显示为1823065.094,查询如下:

SELECT 
    SUM(Z.Actual_Cost ) AS SUM_Actual_Cost
FROM
    (SELECT 
        ...,...,...,...,...,......,...,..,...,
        SUM(COST_REPORTING.Actual_Cost) AS Actual_Cost
    FROM 
        Table_Name AS Table_Name 
    WHERE 
        USAGESTARTDATE >='2018-05-01 00:00:00.000' 
        AND USAGEENDDATE<='2018-05-31 12:00:00.000'
    GROUP BY 
         ...,...,...,...,...,......,...,..,...,) AS Z

Actual_Cost Column数据类型在DB中是浮动的。

为什么所有列的csv都将Actual_Cost总和显示为1817751.612而不是1823065.094,我如何对其进行更正? 预先感谢。

2 个答案:

答案 0 :(得分:0)

尝试在查询(或其他一些大数据类型)中添加明确的CAST(Actual_Cost AS DECIMAL(18,5)),看看是否有帮助

答案 1 :(得分:0)

只需尝试从网格复制所有列,而不是将其另存为文件并将其粘贴到Excel中即可。所有实际成本记录的总和显示1823065.094 ...

我知道这不是Solid Fix,而是Nice WorkAround:)