Oracle:查找 VARCHAR2(50 字节)列的总和

Oracle: Find sum of a VARCHAR2(50 byte) column

我必须计算我的 Oracle 数据库中 VARCHAR2(50 byte) 列的总和。

SQL查询是:

SELECT city, sum(forests) as sum_forests FROM BurnedAreas GROUP BY city

forests 的数据类型为 VARCHAR2(50 byte)

我已经尝试了一些功能,但它们没有用:

  1. TO_NUMBER()

  2. CAST()

我认为问题在于特定列的值具有不同的格式。有些值像 5.37,有些像 14,23 等

有人有解决办法吗?

SELECT city,sum(to_number(replace(translate(forests, '(', '-'), ')', ''))) AS sum_forests
FROM BurnedAreas
GROUP BY city

Generally one need to check how the data flow is there for "forests" column.
Accordingly need to include the condition inside translate(...)

Hope that helps!!!

下面的代码将跳过非数字数据,你不会得到错误。

SELECT city, sum(forests) as sum_forests 
FROM BurnedAreas 
where ISNUMERIC (forests)=1
GROUP BY city

将所有数据插入临时 table,然后求和。因为您的列有“,”,这会使值无效。

SELECT city, replace(forests,',','') as forests 
 into #BurnedAreas
 FROM BurnedAreas 

然后运行下面的数据。

SELECT city, sum(forests) as sum_forests 
FROM #BurnedAreas 
GROUP BY city 

正如我提到的,VARCHAR 列中的数据格式类似于 4.900,25,其中点是百位分隔符和逗号小数点分隔符(2 位小数)。

所以为了求和,我使用了 TO_NUMBER 函数和 更多参数

SUM(TO_NUMBER(forests,'999G999G999D99','NLS_NUMERIC_CHARACTERS='',.'''))