关于货币总和的SQL错误结果值

时间:2016-08-27 13:05:39

标签: sql delphi

使用Delphi X10&绝对数据库SQL92兼容。 我正在使用这个SQL脚本:

  SELECT SUM (CREDIT) AS "SUM_CREDIT",
         SUM (DEBIT) AS "SUM_DEBIT",
         SUM (CREDIT) - SUM (DEBIT) AS Balance,
         YearPay,
         IDCustomer,
         DescCredit
    FROM CostumersPayments
GROUP BY YearPay, IDCustomer, DescCredit
  HAVING (SUM (CREDIT) - SUM (DEBIT)) > 0
ORDER BY YearPay;

我的桌子有大约3000条记录;返回的结果大约有300条记录。

问题在于我获得等额借记,等额贷款,余额为0

结果:

Credit | Debit  | Balance
$ 4,56 | $ 4,56 |    0
$12,12 | $12,12 |    0
$21,6  | $21,6  |    0
.....

大约30个结果记录会发生这种情况,其他结果记录都可以。

这是一种奇怪的行为,因为我想要HAVING (SUM (CREDIT) - SUM (DEBIT)) > 0。所以在搜索了一下之后我发现当AS FLOAT转换时:

         CAST(SUM (CREDIT) AS FLOAT) AS "SUM_CREDIT",
         CAST(SUM (DEBIT) AS FLOAT) AS "SUM_DEBIT",
         CAST(SUM (CREDIT) - SUM (DEBIT) AS FLOAT) AS "SUM_BALANCE"

转换后30条相同记录的返回结果为:

Credit | Debit  | Balance
$ 4,56 | $ 4,56 | 8,88178419700125E-16
$12,12 | $12,12 | 1,77635683940025E-15
$21,6  | $21,60 | 3,5527136788005E-15

在大多数平衡结果中,值为3,5527136788005E-15和7,105427357601E-15。结果0的值为0,000something。我找到了记录并重新输入了借方和贷款。信用价值。结果相同。

字段类型是表格中的货币。

问题出在哪里?

1 个答案:

答案 0 :(得分:0)

我不知道为什么它会返回这些值,但是在检查CREDIT - DEBIT = 0时,快速修复将丢弃所有这些垃圾小数。

 SELECT SUM (CREDIT) AS "SUM_CREDIT",
         SUM (DEBIT) AS "SUM_DEBIT",
         SUM (CREDIT) - SUM (DEBIT) AS Balance,
         YearPay,
         IDCustomer,
         DescCredit
    FROM CostumersPayments
GROUP BY YearPay, IDCustomer, DescCredit
  HAVING cast(SUM (CREDIT) - SUM (DEBIT) as numeric(18, 4)) > 0
ORDER BY YearPay;