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

时间:2017-06-30 06:30:57

标签: sql oracle sum format varchar2

我必须计算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()

  3. 我认为问题在于特定列的值具有不同的格式。有些值类似于5.37,其他值如14,23等。

    有没有人有任何解决方案?

3 个答案:

答案 0 :(得分:0)

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!!!

答案 1 :(得分:0)

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

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

OR

在临时表和放大器中插入所有数据然后做总结。因为你的专栏有","这使得价值无效。

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

然后在数据下面运行。

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

答案 2 :(得分:0)

正如我所提到的,VARCHAR列中的数据格式为4.900,25,其中dot为百分隔符和逗号小数分隔符(2位十进制数字)。

为了找到总和,我使用了TO_NUMBER函数和更多参数

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