对Oracle中字符串中的数字求和

时间:2015-09-16 07:13:42

标签: sql oracle

以下是面试问题,有人可以帮我解决一下吗?

select 'a1b2c3d4e5f6g7' from dual;

输出是给定整数(1 + 2 + 3 + 4 + 5 + 6 + 7)= 28的和。 有什么帮助吗?

4 个答案:

答案 0 :(得分:9)

使用正则表达式仅保留数字,然后连接以添加每个数字

With T
as (select regexp_replace('a1b2c3d4e5f6g7', '[A-Za-z]') as col from dual)
select sum(val)
From
(
select substr(col,level,1) val from t connect by level <= length(col)
)

FIDDLE

答案 1 :(得分:4)

由于只有1位数字,您可以使用SUBSTR()提取其他所有字符:

SQL Fiddle

Oracle 11g R2架构设置

查询1

WITH data ( value ) AS (
  select 'a1b2c3d4e5f6g7' from dual
)
SELECT SUM( TO_NUMBER( SUBSTR( value, 2*LEVEL, 1 ) ) ) AS total
FROM   data
CONNECT BY 2 * LEVEL <= LENGTH( value )

<强> Results

| TOTAL |
|-------|
|    28 |

但是,如果您有两位数字,那么您可以这样做:

查询2

WITH data ( value ) AS (
  select 'a1b2c3d4e5f6g7h8i9j10' from dual
)
SELECT SUM( TO_NUMBER( REGEXP_SUBSTR( value, '\d+', 1, LEVEL ) ) ) AS total
FROM   data
CONNECT BY LEVEL <= REGEXP_COUNT( value, '\d+' )

<强> Results

| TOTAL |
|-------|
|    55 |

答案 2 :(得分:1)

您可以使用regexp_substr精确提取数字,然后将它们相加:

with t as (select 'a1b2c3d4e5f6g7' expr from dual)
select sum(regexp_substr(t.expr, '[0-9]+',1, level)) as col
from dual
connect by level < regexp_instr(t.expr, '[0-9]+',1, level);

示例:

select sum(regexp_substr('a1b2c3d4e5f6g7r22g4', '[0-9]+',1, level)) as col
from dual
connect by level < regexp_instr('a1b2c3d4e5f6g7r22g4', '[0-9]+',1, level);

结果: 54

答案 3 :(得分:1)

此解决方案适用于超过1位的数字,并且数字之间有多少字符无关紧要:

with t as (select 'a1b2c3d4e5f6g7' as str from dual)
  select sum(to_number(regexp_substr(str,'[0-9]+',1,level)))
  from t
  connect by regexp_substr(str,'[0-9]+',1,level) is not null