如何从 SQL Oracle 中的字符串中删除一些数字

How to cut from string some number in SQL Oracle

我有问题 在 oracle 中剪切一些文本(数字)

我必须在第一个数字'1-9'之前只取第一个'0'的数字,但在这个我必须取的也是'0'我需要'0000 1204 '

示例'00007645'、'00012305'、'00000078'和'0000120400000123'或'000012340000012300040678'

来自序列号的 len 始终是相同的 8 或 16 或 24 等,并且从每个 8 我必须删除带有“0”的第一个序列并取单独的数字

有人能帮帮我吗?

您可以将 REGEXP_REPLACE() 函数与 '[^1-9]' 模式一起使用,例如

SELECT REGEXP_REPLACE(col,'[^1-9]')
  FROM t -- your table

使用LTRIM:

SELECT LTRIM(seq_num, '0')
FROM yourTable;

或者,使用 REGEXP_REPLACE:

SELECT REGEXP_REPLACE(seq_num, '^0+', '')
FROM yourTable;

根据您的评论,您希望将原始文本拆分为多个值,然后去除每个值的前导零。您引用了多列,这没关系,但您必须知道可以拥有多少列 - 即要知道原始字符串的最大长度。

例如,最大长度为 24,您可以拆分为:

select
  regexp_substr(text, '\d{8}', 1, 1) as chunk1,
  regexp_substr(text, '\d{8}', 1, 2) as chunk2,
  regexp_substr(text, '\d{8}', 1, 3) as chunk3
...

然后要么只是删除前导零以保留为字符串:

select
  ltrim(regexp_substr(text, '\d{8}', 1, 1), '0') as str1,
  ltrim(regexp_substr(text, '\d{8}', 1, 2), '0') as str2,
  ltrim(regexp_substr(text, '\d{8}', 1, 3), '0') as str3

或转换为数字:

select,
  to_number(regexp_substr(text, '\d{8}', 1, 1)) as num1,
  to_number(regexp_substr(text, '\d{8}', 1, 2)) as num2,
  to_number(regexp_substr(text, '\d{8}', 1, 3)) as num3

在每种情况下,要处理更长的字符串,您需要添加更多的列表达式,增加 occurrence 数字(和列名称)。

将您的示例数据放入 table t:

select text,
  to_number(regexp_substr(text, '\d{8}', 1, 1)) as num1,
  to_number(regexp_substr(text, '\d{8}', 1, 2)) as num2,
  to_number(regexp_substr(text, '\d{8}', 1, 3)) as num3
from t
TEXT NUM1 NUM2 NUM3
00001204 1204
00007645 7645
00012305 12305
00000078 78
0000120400000123 1204 123
000012340000012300040678 1234 123 40678
00000010 10
0000001000000100 10 100

如果你想要每个值一个,你可以使用分层查询或递归子查询分解:

with rcte (text, chunk_num, chunk, remainder) as (
  select text, 1, substr(text, 1, 8), substr(text, 9)
  from t
  union all
  select text, chunk_num + 1, substr(remainder, 1, 8), substr(remainder, 9)
  from rcte
  where remainder is not null
)
select text, chunk_num, chunk, ltrim(chunk, '0') as str, to_number(chunk) as num
from rcte
order by text, chunk_num
TEXT CHUNK_NUM CHUNK STR NUM
00000010 1 00000010 10 10
0000001000000100 1 00000010 10 10
0000001000000100 2 00000100 100 100
00000078 1 00000078 78 78
00001204 1 00001204 1204 1204
0000120400000123 1 00001204 1204 1204
0000120400000123 2 00000123 123 123
000012340000012300040678 1 00001234 1234 1234
000012340000012300040678 2 00000123 123 123
000012340000012300040678 3 00040678 40678 40678
00007645 1 00007645 7645 7645
00012305 1 00012305 12305 12305

db<>fiddle