T-Sql求和正浮点值和负浮点值

时间:2017-11-04 18:53:01

标签: sql sql-server tsql select sum

WITH CTE AS
(
    SELECT 
        ITM.CODE AS ITMCODE,
        CASE 
           WHEN IOCODE IN (1,2) THEN AMOUNT 
           ELSE AMOUNT * -1 
        END AS AMOUNT
    FROM 
        ITEMLINE ITL, ITEMS ITM 
    WHERE 
        ITL.ITEMREF = ITM.LOGICALREF 
        AND ITM.CODE = '123'
)
SELECT 
    ITMCODE, SUM(AMOUNT)  
FROM 
    CTE 
GROUP BY 
    ITMCODE

CTE返回五行,金额为float。 Sum函数返回2,27373675443232E-13。如果我不使用金额* -1则没有问题,返回值是正常的。是什么导致这个?这从视图返回,我不能改变它被禁止的视图,我必须修复这些值。五行的值为5,6,7,8,9。感谢。

1 个答案:

答案 0 :(得分:0)

首先,您的查询过于复杂。只是做:

SELECT ITM.CODE AS ITMCODE,
       SUM(CASE WHEN IOCODE IN (1, 2) THEN AMOUNT ELSE AMOUNT * -1 
           END) AS AMOUNT
FROM ITEMLINE ITL JOIN
     ITEMS ITM 
     ON ITL.ITEMREF = ITM.LOGICALREF 
WHERE ITM.CODE = '123'
GROUP BY ITM.CODE;

其次,这是浮点数的本质。您应该将金额存储为decimal / numeric,固定点数。

您应该能够通过转换为合适的类型来获得您想要的内容:

SELECT ITM.CODE AS ITMCODE,
       CONVERT(DECIMAL(10, 2),  -- or whatever
               SUM(CASE WHEN IOCODE IN (1, 2) THEN AMOUNT ELSE AMOUNT * -1 
                   END)
              ) AS AMOUNT
FROM ITEMLINE ITL JOIN
     ITEMS ITM 
     ON ITL.ITEMREF = ITM.LOGICALREF 
WHERE ITM.CODE = '123'
GROUP BY ITM.CODE;

但是,我建议您修复表格中的数据,以更适合货币金额的方式存储金额,所以:

alter table itemline alter column amount decimal(12, 4);  -- or whatever