算术溢出或其他算术异常发生的解决方案?

时间:2013-09-25 14:02:07

标签: sql db2 aggregate-functions

我使用db2,不知道是什么版本。尝试对表进行求和时,我收到溢出错误。我认为我可以将总和投入BIGINT,这似乎适用于总和,但我希望得到一个百分比,当我转向BIGINT时,我的数据是不准确的。如何获得Percent_DeliveredB / A的准确百分比?将分子和分母转换为BIGINT并除以百分比并不能给我正确的结果。

这是我的剧本:

SELECT 
FAT.DIM_BUILDING_ID,
FAT.BUILDING_NAME,
SUM(CAST(FAT.AMOUNT AS BIGINT)) AS SALES_SUM,
SUM(CAST(FAT.ORDERS AS BIGINT)) AS ORDERS_SUM,
SUM(CAST(FAT.CAPABILITY AS BIGINT)) AS CAPABILITY_SUM,
SUM(FAT.ORDERS_B)/sum(FAT.Amount) AS Percent_DeliveredB,
SUM(FAT.ORDERS_A)/sum(FAT.Amount) AS Percent_DeliveredA,
SUM(CAST(FTS.GROUP_A AS BIGINT)) AS GROUP_A,
SUM(CAST(FTS.GROUP_B AS BIGINT)) AS GROUP_B,
SUM(CAST(FTS.GROUP_C AS BIGINT)) AS GROUP_C  

FROM ORDERS AS FAT
INNER JOIN GROUPS AS FTS ON FAT.DIM_PROJECT_ID = FTS.DIM_PROJECT_ID
GROUP BY FAT.DIM_BUILDING_ID, FAT.BUILDING_NAME;

我尝试了以下内容,但是百分比返回0。

SUM(CAST(FAT.ORDERS_B AS BIGINT))/sum(CAST(FAT.Amount AS BIGINT)) AS Percent_DeliveredB

3 个答案:

答案 0 :(得分:3)

我能够将正确的结果转换为双倍。

SUM(CAST(FAT.ORDERS_B AS DOUBLE))/sum(CAST(FAT.Amount AS DOUBLE)) AS Percent_DeliveredB,

答案 1 :(得分:2)

它给你一个正确的结果,因为任何小于1的值,当转换为整数(或BIGINT)时,显然会被截断为0。如果您期望得到小数,请使用DECIMAL或FLOAT数据类型:

cast(SUM(FAT.ORDERS_B) as decimal(10,2)) / 
cast(sum(FAT.Amount) as decimal(10,2)) AS Percent_DeliveredB

当然,请根据您的需要使用正确的精度。

答案 2 :(得分:0)

在非常大的表上使用select count(*)时,我遇到了相同的错误。

我通过使用count_big(*)来解决此问题,它可以处理超过2.147.483.647(MAX_LONGINT_INT SQL限制)的计数。