我有一个查询结果,我应该得到一列的最后一位数字,比如“term”
The value of column term can be like:
'term' 'number' (output)
---------------------------
xyz012 12
xyz112 112
xyz1 1
xyz02 2
xyz002 2
xyz88 88
注意:不限于以上场景,但要求最后3个或更少的字符可以是数字
我使用的函数:to_number(substr(term.name,-3))
(最初我假设要求最后 3 个字符总是数字,但我错了)
我正在使用 to_number 因为如果最后 3 位数字是“012”那么数字应该是“12” 但是正如在某些特定情况下可以看到的那样,例如“xyz88”、“xyz1”)会给出
ORA-01722: invalid number
如何使用 substr 或 regexp_substr 实现此目的?
没有过多探索 regexp_substr。
最佳答案
使用REGEXP_SUBSTR
,
select column_name, to_number(regexp_substr(column_name,'\d+$'))
from table_name;
- \d 匹配数字。与 + 一起成为一个或多个数字的组。
- $ 匹配行尾。
- 将它们放在一起,这个正则表达式提取字符串末尾的一组数字。
更多详情 here .
演示 here .
关于sql - 使用 oracle sql substr 获取最后一位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17944800/