Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

sql - Get value between 2nd and 3rd comma

I am trying to extract the state from an address where everything is in one column, heres an example:

2901 MAIN ST,CORNING,NY,14830

I have been trying to figure out how to do it with the substr and instr together, but I cant seem to get the hang of instr. Here is what I have so far:

select substr('hello,hello,NY,11725-1234',1,instr('hello,hello,NY,11725-1234',',',2,3))
from dual;

I thought it would start at the second comma and end at the 3rd and get my everything in between, but that doesnt seem to be the case.

Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
select 
  regexp_substr('2901 MAIN ST,CORNING,NY,14830', '(.*?,){2}(.*?),', 1, 1, '', 2) 
from dual

In general,

n_th_component := 
  regexp_substr(string, '(.*?,){'||(n-1)||'}([^,]*)', 1, 1, '', 2);

Example:

select 
  n,  
  regexp_substr('2901 MAIN ST,CORNING,NY,14830', 
                '(.*?,){'||(n-1)||'}([^,]*)', 1, 1, '', 2)
from (select level n from dual connect by level <= 4)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...