2017-10-20 63 views
0

我的要求是从字符串中获取第二个和第三个'/'之间的数据(/从右到左考虑)和下面是示例示例。如何获取第二个和第三个字符串之间的值/从字符串(/从右到左考虑)

1.My string is RAM/ESH/BA/BU/MOR/SA and output to be derived is BU 
2.My string is RAM/ESH/BA/MOR/SA and output to be derived is BA 
3.My String is TR/IV/NI and output to be derived is TR 

请帮我查询。

+0

在你的最后一个例子中没有“third”/。你的意思是/ **还是字符串**的开始? – mathguy

回答

0

以下是一种方法 - 只使用标准字符串函数(无正则表达式)以获得最佳性能。注意使用INSTR,-1作为第三个参数(指示位置);负数表示从字符串的末尾开始计数(从右到左)。

我增加了两个输入字符串来测试正确的处理。如果第二个和第三个之间绝对没有任何内容,则“标记”必须为NULL。如果输入字符串中没有至少两个/,则相同。正如我在评论中解释的那样,您错误地指出了这个问题 - 输入中至少需要两个斜杠;如果只有两个,则从输入字符串的开始处取得“标记”。

with 
    inputs (str) as (
    select 'RAM/ESH/BA/BU/MOR/SA' from dual union all 
    select 'RAM/ESH/BA/MOR/SA' from dual union all 
    select 'TR/IV/NI'    from dual union all 
    select 'ST//TUL/SV'   from dual union all 
    select 'MOR/SA'    from dual 
) 
-- End of simulated inputs (for testing only, not part of the solution). 
-- SQL query begins BELOW THIS LINE. Use your actual table and column names. 
select str, 
     substr(str, instr(str, '/', -1, 3) + 1, 
        instr(str, '/', -1, 2) - instr(str, '/', -1, 3) - 1 
      ) as third_token_from_right 
from inputs; 

STR     THIRD_TOKEN_FROM_RIGHT 
-------------------- ---------------------- 
RAM/ESH/BA/BU/MOR/SA BU 
RAM/ESH/BA/MOR/SA  BA 
TR/IV/NI    TR 
ST//TUL/SV 
MOR/SA 
相关问题