Oracle奇怪的SUM行为

时间:2015-01-15 09:54:26

标签: sql oracle

我有两个问题,根据我的理解应该提供相同的结果,但事实并非如此。很明显,我在这里遗漏了一些重要的观点,我希望你能帮助我。

  1. 查询(我认为这是错误的):

      SELECT SUM(a.amount) AS A_SUM ---10 727.470
      FROM billdetail a
      INNER JOIN bill c
        ON (a.bill_id = c.bill_id)
      INNER JOIN dates d
        ON (c.date_id = d.date_id)
      WHERE d.year                = '2014'
        AND c.status        <> 'D'
        AND a.status        <> 'D';
    
  2. 查询:

    SELECT SUM(C_SUM) ---10 754.279
    FROM
      (
      SELECT SUM(a.amount) AS C_SUM
      FROM billdetail a
      INNER JOIN bill c
        ON (a.bill_id = c.bill_id)
      INNER JOIN dates d
        ON (c.date_id = d.date_id)
      WHERE d.year                = '2014'
        AND c.status        <> 'D'
        AND a.status        <> 'D'
      GROUP BY c.bill_id
      );
    
  3. 正如你所看到的,查询1给了我10 727.470,其中查询2给了我10 754.279,所以少了27。

    你能解释一下为什么会这样吗?我以为我在这里做同样的事情:只选择2014年的账单,然后从那里抓住所有账单,并总结金额。但显然我在这里有一些理解问题,希望你能帮助我。

1 个答案:

答案 0 :(得分:2)

您可能正在点击&#34;错误4604970错误的结果与&#39;哈希组的结果是&#39;已启用聚合&#34;。您可以通过运行alter session set "_gby_hash_aggregation_enabled"=false;来避免该错误。这是一个简单的bug测试案例,这些年后可悲的是仍然存在。

SQL> select stddev(test), count(distinct test) from
  2  (
  3      select 7/9 test from dual
  4      union all
  5      select 7/9 test from dual
  6  );
select stddev(test), count(distinct test) from
*
ERROR at line 1:
ORA-01428: argument '-.00000000000000000000000000000000000001' is out of range


SQL> alter session set "_gby_hash_aggregation_enabled"=false;

Session altered.

SQL> select stddev(test), count(distinct test) from
  2  (
  3      select 7/9 test from dual
  4      union all
  5      select 7/9 test from dual
  6  );

STDDEV(TEST) COUNT(DISTINCTTEST)
------------ -------------------
           0                   1