[英]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
有什么方法可以在 Oracle SQL 中實現上述目標
您可以使用regexp_substr()
:
select replace(replace(regexp_substr(name, ',([^,]+)\]$'), ',', ''), ']', '') as last_name
或者使用regexp_replace()
:
select regexp_replace(name, '^(.*,|[\[a-zA-Z]+)([^,]*)\]$', '\2')
這是db<>小提琴。
我應該注意到在一個字符串中存儲多個值是一個壞主意。 SQL 和 Oracle 有許多比重載字符串定義更好的解決方案。
您可以將regexp_substr
與regexp_count
oe instr
一起使用以達到所需的結果,如下所示:
Select case when regexp_count(name, ',') > 0
then replace(regexp_substr(name, '[^,]+$'),']','')
end
From your_table
干杯!!
此選項使用嵌套的regexp_substr
:
]
括號之間的子字符串。 例如,對於[sundaar,j]
,它返回,j]
,
和]
之間的詞所以:
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.