I have a table called tbl_notes needs to use Oracle SQL. It has 2 columns ID and Notes.
Select * from tbl_notes where id > 11 and id < 15
shows:
ID NOTES
12 Item on shipment to MEE
13 MATARIAL ON THE WAY TO M44, MTT, MZZ
14 MVV has shipments coming to M99
I want it to show:
ID Locations
12 MEE
13 M44
13 MTT
13 MZZ
14 MVV
14 M99
This is a bit of a nasty data model and trying to extract those values is likely to lead to false positives, but you can make a stab at it using regexp_substr()
and a hierarchical query (or recursive CTE) - essentially treating it as delimited text:
select id, notes, regexp_substr(notes, '(M[[:alnum:]]{2})([^[:alnum:]]|$)', 1, level, null, 1) as locations
from tbl_notes
connect by level < regexp_count(notes, '(M[[:alnum:]]{2})([^[:alnum:]]|$)')
and id = prior id
and prior sys_guid() is not null
which with your data gets:
ID NOTES LOCATIONS
-- ------------------------------------ ---------
12 Item on shipment to MEE MEE
13 MATARIAL ON THE WAY TO M44, MTT, MZZ M44
13 MATARIAL ON THE WAY TO M44, MTT, MZZ MTT
13 MATARIAL ON THE WAY TO M44, MTT, MZZ MZZ
14 MVV shipments coming to M99 MVV
14 MVV shipments coming to M99 M99
But all of your example match the 'next 2 repeating' part; if you introduce another row that doesn't match that then that value will be picked up too:
ID NOTES LOCATIONS
-- ------------------------------------ ---------
...
15 MVA shipments coming to M999 MVA
You can use a subquery and substr check to eliminate that:
select id, locations
from (
select id, regexp_substr(notes, '(M[[:alnum:]]{2})([^[:alnum:]]|$)', 1, level, null, 1) as locations
from tbl_notes
connect by level <= regexp_count(notes, '(M[[:alnum:]]{2})([^[:alnum:]]|$)')
and id = prior id
and prior sys_guid() is not null
)
where substr(locations, 2, 1) = substr(locations, 3, 1)
which gets:
ID LOCATIONS
-- ---------
12 MEE
13 M44
13 MTT
13 MZZ
14 MVV
14 M99
However, this is likely to break at some point, so you will probably end up repeatedly tweaking and adapting as you hit edge cases.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.