我想创建变量:在$
之前提取数字的数字Name | Number
abc1/12 $ | 12
12av 12$ | 12
114$-bgv | 114
我有一个问题:
select Name, substring(Name FROM '%#"[0-9]+#"$%' FOR '#') as Number
from table;
但它返回:
Name | Number
abc1/12 $ |
12av 12$ | 2
114$-bgv | 4
有什么想法吗?
答案 0 :(得分:1)
使用regexp_matches()
:
select
(regexp_matches(Name, '^(.*[^\d]+){0,1}(\d+)\$'))[2] as Number
from (
select 'abc1/12$' as Name
union select '12av 12$'
union select 'bgv-114$'
union select '124$'
) t
或substring()
select
coalesce(substring(Name FROM '.*[^\d]+(\d+)\$'), '') ||
coalesce(substring(Name FROM '^(\d+)\$'), '') as Number
from (
select 'abc1/12$' as Name
union select '12av 12$'
union select 'bgv-114$'
union select '124$'
) t