SUM函数无法正确添加

时间:2015-07-09 15:03:04

标签: sql-server sql-server-2008 tsql stored-procedures

我有一张表,我可以从中计算特定列中值的总和。该表是:

PayTable

Amount       GRPS        
65,025.00    355
-2,500.00    355
7,014.40     355
725.62       355
241.67       355
1,209.57     355
241.87       355
241.87       355

查询是:

SELECT   GRPS,SUM(Amount) AS AMT into AmtTab FROM PayTable GROUP BY  GRPS

这应该给我72200的总和,但它返回72199.999999999985。但是,它仅对组355执行此操作,对于其他组,计算正确

2 个答案:

答案 0 :(得分:1)

我不确定您的数据类型。但请参阅以下返回值的示例。在MSSQL 2012中,您的情况似乎与数据类型REAL相对应。 MONEY,FLOAT,DECIMAL,DOUBLE PRECISION 返回72200.00 REAL 返回72199.9998321533。见下文:

CREATE TABLE #tempso (Amount money, GRPS int);

INSERT INTO #tempso(Amount, GRPS) VALUES
('65025.00',355),
('-2500.00',355),
('7014.40',355),
('725.62',355),
('241.67',355),
('1209.57',355),
('241.87',355),
('241.87',355)

SELECT GRPS,SUM(Amount) AS AMT FROM #tempso GROUP BY  GRPS

ALTER TABLE #tempso ALTER COLUMN Amount float
SELECT GRPS,SUM(Amount) AS AMT FROM #tempso GROUP BY  GRPS

ALTER TABLE #tempso ALTER COLUMN Amount decimal(10,2)
SELECT GRPS,SUM(Amount) AS AMT FROM #tempso GROUP BY  GRPS

ALTER TABLE #tempso ALTER COLUMN Amount DOUBLE PRECISION
SELECT GRPS,SUM(Amount) AS AMT FROM #tempso GROUP BY  GRPS

        --------------- 
RETURNS:|355 72200.00 |
        ---------------

ALTER TABLE #tempso ALTER COLUMN Amount REAL
SELECT GRPS,SUM(Amount) AS AMT FROM #tempso GROUP BY  GRPS

        ----------------------  
RETURNS:|355 72199.9998321533 |
        ----------------------

DROP TABLE #tempso

您可能想要更改列数据类型(如果它不是所需的类型,可能是从SQL Studio的下拉菜单中错误设置的,或者)将该值作为上述数据类型之一进行CAST返回需要 72200.00

答案 1 :(得分:0)

谢谢@Andy Korneyev ...... sum(cast (amount as decimal (10,2)))解决了问题!