繁体   English   中英

需要在 Oracle 中进行 SQL 查询以从逗号分隔的字符串中获取姓氏

[英]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_substrregexp_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM