2017-06-26 32 views
1

我必須在使用Oracle SQL的表內找到四個數字的第一個序列。使用Oracle SQL查找字符串中的前四個數字

裏面的input_file_name列,我們可以找到值:

RVSP_040517.M 
SERIES_040517_CP.TXT 
SAUDE_O10N0505.M 
SERIES_040517.txt 
RVSP_080517.M 
SERIES_080517_CP.TXT 

我們可以看到,有一個數字之前的羣體,但四個數字從左邊第一組就是我想要的。我想用這個日期(4)數字創建一個新列。

我該怎麼辦呢?

我從這個表期待的結果是:

0405 
0405 
0505 
0405 
0805 
0805 

我試圖用INSTR,但它不工作

回答

2
select ..., regexp_substr(input_file_name, '\d{4}') as day_month, ... 
from ... 

演示(多帶幾個字符串顯示當沒有任何四個連續數字的子串或者這種子串的多次出現時會發生什麼情況):

with 
    test_data (input_file_name) as (
     select 'RVSP_040517.M'  from dual union all 
     select 'SERIES_040517_CP.TXT' from dual union all 
     select 'SAUDE_O10N0505.M'  from dual union all 
     select 'SERIES_040517.txt' from dual union all 
     select 'RVSP_080517.M'  from dual union all 
     select 'SERIES_080517_CP.TXT' from dual union all 
     select 'mathguy wins'   from dual union all 
     select 'GOOD_031.pdf'   from dual union all 
     select 'FOUR_DIGITS_123_4' from dual union all 
     select 'A22409_11230.cpp'  from dual 
    ) 
-- End of simulated data (for testing purposes only, not part of the solution). 
-- SQL query begins BELOW THIS LINE. 
select input_file_name, regexp_substr(input_file_name, '\d{4}') as day_month 
from test_data 
; 

INPUT_FILE_NAME  DAY_MONTH   
-------------------- ------------ 
RVSP_040517.M   0405     
SERIES_040517_CP.TXT 0405     
SAUDE_O10N0505.M  0505     
SERIES_040517.txt  0405     
RVSP_080517.M   0805     
SERIES_080517_CP.TXT 0805     
mathguy wins        
GOOD_031.pdf        
FOUR_DIGITS_123_4 
A22409_11230.cpp  2240 
相關問題