Oracle:在一个字符串中找到最大的数字

时间:2018-07-09 16:48:40

标签: oracle plsql

asdfAB98:(hjkl,)AB188(uiop)uuuAB78:jknd之类的表格的列中有一些字符串。我想知道如何在每一行的这样的字符串中提取最大的数字。例如,此处最大的数字是188(在1889878中)。

由于我感兴趣的数字始终在AB之后,因此我在考虑使用regexp_substr。不幸的是,我不确定如何使其输出多行,以便可以使用max子句。 PLSQL语言也很好。如果您有想法,请给我看一个简单的例子。预先谢谢你!

2 个答案:

答案 0 :(得分:3)

您可以将字符串标记为所有数字部分,然后找到最大值:

select max(to_number(
    regexp_substr('sdfAB98:(hjkl,)AB188(uiop)uuuAB78:jknd', '(\d+)', 1, level))
  ) as max_value
from dual
connect by regexp_substr('sdfAB98:(hjkl,)AB188(uiop)uuuAB78:jknd', '(\d+)', 1, level)
  is not null;

 MAX_VALUE
----------
       188

select max(to_number(
    regexp_substr('sdfAB98:(hjkl,)AB188(uiop)uuuAB78:jknd', '(\d+)', 1, level, null, 1))
  ) as max_value
from dual
connect by level <= regexp_count('sdfAB98:(hjkl,)AB188(uiop)uuuAB78:jknd', '\d+');

 MAX_VALUE
----------
       188

如果您需要从多行中获取值,则需要connect-by来匹配ID,并且还需要包含对非确定性函数的引用以防止循环;在CTE中有两个值:

with your_table (id, str) as (
  select 1, 'sdfAB98:(hjkl,)AB188(uiop)uuuAB78:jknd' from dual
  union all select 2, '123abc456abc78d9' from dual
)
select id, max(to_number(regexp_substr(str, '(\d+)', 1, level, null, 1))) as max_value
from your_table
connect by prior id = id
and prior dbms_random.value is not null
and level <= regexp_count(str, '\d+')
group by id;

        ID  MAX_VALUE
---------- ----------
         1        188
         2        456

答案 1 :(得分:1)

或者(对于亚历克斯回答),如果有多行:

SQL> with your_table (id, str) as (
  2    select 1, 'sdfAB98:(hjkl,)AB188(uiop)uuuAB78:jknd' from dual
  3    union all select 2, '123abc456abc78d9' from dual
  4  )
  5  select id, max(to_number(regexp_substr(str, '\d+', 1, column_value))) max_num
  6  from your_table,
  7       table(cast(multiset(select level from dual
  8                           connect by level <= regexp_count(str, '\d+')
  9                          ) as sys.odcinumberlist))
 10  group by id;

        ID    MAX_NUM
---------- ----------
         1        188
         2        456

SQL>