[英]select string after second to the last occurrence of a character
尝试学习一些高级 Oracle Sql 公式,我有一个客户字段,
父客户:Child1 客户:孙客户:GreatGrandchild 客户
我需要一个可以给我的公式
孙客户 : GreatGrandchild 客户
该字段可能在 3 或 4 个关系之间变化,所以我只想要倒数第二个之后的数据:
任何援助将不胜感激!
您可以通过SUBSTR
和INSTR
执行此操作,如下所示:
WITH your_table AS (SELECT 'Parent Customer : Child1 Customer : Grandchild Customer : GreatGrandchild Customer' your_field FROM dual)
SELECT your_field,
SUBSTR(your_field, INSTR(your_field, ' : ', -1, 2) + 3) your_field_part
FROM your_table;
YOUR_FIELD YOUR_FIELD_PART
-------------------------------------------------------------------------------- ----------------------------------------------
Parent Customer : Child1 Customer : Grandchild Customer : GreatGrandchild Custom Grandchild Customer : GreatGrandchild Customer
这是通过首先找到:
字符串开头的位置,从最后一个字符开始(由第三个参数 ( -1
) 确定,因为它是负数,表示我们从字符串末尾的第一个字符开始)的开头),然后将字符串从该字符 + 3(因为:
长度为 3 个字符)到字符串的末尾。
使用substr()
和instr()
。 Instr 为您提供以:
开头的子字符串的数字,然后这些数字可以在 substr 中用作参数以仅返回您需要的源字符串的一部分。 Instr 还允许您指定该子字符串的出现次数(作为第三个参数)。
select
instr(customer,':',1,1) first
, instr(customer,':',1,2) second
, instr(customer,':',1,3) third
, substr(customer,instr(customer,':',1,2)+2) second_and_last_part
, substr(customer,instr(customer,':',1,2)+2, instr(customer,':',1,3)-instr(customer,':',1,2)-2) second_last_part
, substr(customer,instr(customer,':',1,3)+2) last_part
from (
select 'Parent Customer : Child1 Customer : Grandchild Customer : GreatGrandchild Customer' as customer from dual
)
注意:您在上面看到的+2
的使用是因为每个:
的字符位置后面还跟着一个空格,所以为了忽略这两个,我们加了 2。
只需混合和匹配具有不同参数的各种函数调用,即可将原始字符串分成几部分,如上面的查询所示:
+-------+--------+-------+------------------------------------------------+--------------------------+----------------------+
| FIRST | SECOND | THIRD | SECOND_AND_LAST_PART | LAST_PART | SECOND_LAST_PART |
+-------+--------+-------+------------------------------------------------+--------------------------+----------------------+
| 17 | 35 | 57 | Grandchild Customer : GreatGrandchild Customer | GreatGrandchild Customer | Grandchild Customer |
+-------+--------+-------+------------------------------------------------+--------------------------+----------------------+
INSTR(string, substring [, start_position [, th_appearance ] ] ) ref
SUBSTR(string, start_position [, length ] ) ref
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.