[英]Need SQL query in Oracle to fetch last name from the string separated by comma
name
------
[pratik]
[Ishaan,llc,ltd]
[sundaar,j]
[sid,h]
output should be like:
name last_name
------ ---------
[pratik] null
[Ishaan,llc,ltd] ltd
[sundaar,j] j
[sid,h] h
is there any way by which we can achieve the above in Oracle SQL有什么方法可以在 Oracle SQL 中实现上述目标
You can use regexp_substr()
:您可以使用regexp_substr()
:
select replace(replace(regexp_substr(name, ',([^,]+)\]$'), ',', ''), ']', '') as last_name
Or using regexp_replace()
:或者使用regexp_replace()
:
select regexp_replace(name, '^(.*,|[\[a-zA-Z]+)([^,]*)\]$', '\2')
Here is the db<>fiddle. 这是db<>小提琴。
I should note that storing multiple values in a string is a bad idea.我应该注意到在一个字符串中存储多个值是一个坏主意。 SQL and Oracle have many better solutions than overloading the definition of a string. SQL 和 Oracle 有许多比重载字符串定义更好的解决方案。
You can use the regexp_substr
with regexp_count
oe instr
to achieve the desired result as following:您可以将regexp_substr
与regexp_count
oe instr
一起使用以达到所需的结果,如下所示:
Select case when regexp_count(name, ',') > 0
then replace(regexp_substr(name, '[^,]+$'),']','')
end
From your_table
Cheers!!干杯!!
This option uses nested regexp_substr
:此选项使用嵌套的regexp_substr
:
]
bracket.内部返回最后一个逗号和]
括号之间的子字符串。 For example, for [sundaar,j]
, it returns ,j]
例如,对于[sundaar,j]
,它返回,j]
,
and ]
外层返回一个介于,
和]
之间的词So:所以:
SQL> with test (name) as
2 (select '[pratik]' from dual union all
3 select '[Ishaan,llc,ltd]' from dual union all
4 select '[sundaar,j]' from dual union all
5 select '[sid,h]' from dual
6 )
7 select name,
8 regexp_substr(regexp_substr(name, ',\w+]$'), '\w+') last_name
9 from test;
NAME LAST_NAME
---------------- --------------------
[pratik]
[Ishaan,llc,ltd] ltd
[sundaar,j] j
[sid,h] h
SQL>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.