我必须计算Oracle数据库中VARCHAR2(50 byte)
列的总和。
SQL查询是:
SELECT city, sum(forests) as sum_forests FROM BurnedAreas GROUP BY city
列forests
的数据类型为VARCHAR2(50 byte)
我已经尝试了一些功能,但他们没有工作:
TO_NUMBER()
CAST()
我认为问题在于特定列的值具有不同的格式。有些值类似于5.37,其他值如14,23等。
有没有人有任何解决方案?
答案 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='',.'''))