Oracle SQL总和有时会返回双倍值

时间:2016-03-11 05:58:42

标签: sql oracle toad

在Oracle 11上使用TOAD时遇到了一个有趣的结果。同样的查询有时会返回正确的值,有时则不会。没有分组。没有加入。我错过了什么吗?

查询将所有数字转换为数字值,然后多个3或多个1取决于它们的位置,然后求和。

该字段定义为" device_id VARCHAR2(25);"

在查询之后返回182,这是正确值91的两倍。如果将条件更改为ii.device_id =' 20637320050504',则它的正确值为67.

select sum(to_number(substr( ii. device_id, 1, 1 ))*3 +
               to_number(substr(ii. device_id, 13, 1 ))*3 + to_number(substr(ii. device_id, 12, 1 )) +
               to_number(substr(ii. device_id, 11, 1 ))*3 + to_number(substr(ii. device_id, 10, 1 )) +
               to_number(substr(ii. device_id, 9, 1 ))*3 + to_number(substr(ii. device_id, 8, 1 )) +
               to_number(substr(ii. device_id, 7, 1 ))*3 + to_number(substr(ii. device_id, 6, 1 )) +
               to_number(substr(ii. device_id, 5, 1 ))*3 + to_number(substr(ii. device_id, 4, 1 )) +
               to_number(substr(ii. device_id, 3, 1 ))*3 + to_number(substr(ii. device_id, 2, 1 )) ) as total
from identifier ii
where ii. device_id = '55019315060289'

我尝试从我的表定义中修改查询,如下所示,结果是正确的。

select sum(to_number(substr( '55019315060289', 1, 1 ))*3 +
           to_number(substr('55019315060289', 13, 1 ))*3 +  to_number(substr('55019315060289', 12, 1 )) +
           to_number(substr('55019315060289', 11, 1 ))*3 +  to_number(substr('55019315060289', 10, 1 )) + 
           to_number(substr('55019315060289', 9, 1 ))*3 +   to_number(substr('55019315060289', 8, 1 )) +
           to_number(substr('55019315060289', 7, 1 ))*3 +   to_number(substr('55019315060289', 6, 1 )) +
           to_number(substr('55019315060289', 5, 1 ))*3 +   to_number(substr('55019315060289', 4, 1 )) +
           to_number(substr('55019315060289', 3, 1 ))*3 +   to_number(substr('55019315060289', 2, 1 )) ) as total 
from dual;

看起来它不是TOAD或Oracle问题,但我无法弄清楚我做错了什么。谢谢。

1 个答案:

答案 0 :(得分:1)

记下数据类型可能支持的"值范围"。无符号整数不能保持值55019315060289,无符号整数可以容纳的最大值是2147483647