使用SUM减法无法正常工作

时间:2016-05-17 10:26:45

标签: mysql

按照我的查询:

SELECT SUM(t*q) as first, 
SUM(s*q) AS second, 
SUM(t*q)-SUM(s*q) AS firstminussecond 
FROM my_table

结果是:

first = 9010.56
second = 8664 
firstminussecond = 346.5599999999995 (this should be 346.56!)

为什么firstminussecond不正确?怎么解决这个问题?

5 个答案:

答案 0 :(得分:2)

您可以尝试:

SELECT SUM(t*q) as first, 
SUM(s*q) AS second, 
FORMAT(SUM(t*q)-SUM(s*q),2) AS firstminussecond 
FROM my_table

答案 1 :(得分:2)

SELECT SUM(t*q) as first, 
SUM(s*q) AS second, 
cast(SUM(t*q)-SUM(s*q) as decimal(5,2)) AS firstminussecond 
FROM my_table

答案 2 :(得分:1)

试试这个,

    SELECT 
            ROUND(SUM(t*q),2) as first, 
            ROUND(SUM(s*q),2) AS second, 
            (
             ROUND(SUM(t*q),2)-
             ROUND(SUM(s*q),2)
            ) AS firstminussecond 
    FROM my_table

OR

    SELECT 
            ROUND(SUM(t*q),2) as first, 
            ROUND(SUM(s*q),2) AS second, 
            ROUND(
                    (ROUND(SUM(t*q),2)-
                     ROUND(SUM(s*q),2))
                 ,2) AS firstminussecond 
    FROM my_table

答案 3 :(得分:0)

您需要使用ROUND功能。

SELECT SUM(t*q) AS first, 
SUM(s*q) AS second, 
ROUND(SUM(t*q)-SUM(s*q), 2) AS firstminussecond 
FROM my_table

答案 4 :(得分:0)

我认为我找到了正确的解决方案,我将列const&t的数据类型更改为sDECIMAL(10,2)更改为q。现在INT(11)是正确的。