1

What can I apply as function?

Query:

Select x, f(y) from table where y like '%ab%cd%ef';

sample table(y is sorted alphabatically)

x.  y
1   ab
2   ab,cd
3   cd,ef
4   ab,ef,gh,yu
5   de,ef,rt

Expected Output:

Output:

x y
1 ab
2 ab,cd
3 cd,ef
4 ab,ef
5 ef

2 Answers 2

1

Use regexp_substr function with connect by level expressions as

with tab(x,y) as
(
 select 1,'ab'          from dual union all
 select 2,'ab,cd'       from dual union all
 select 3,'cd,ef'       from dual union all 
 select 4,'ab,ef,gh,yu' from dual union all 
 select 5,'de,ef,rt'    from dual
), tab2 as
( 
Select x, regexp_substr(y,'[^,]+',1,level) as y 
  from tab  
 connect by level <= regexp_count(y,',') + 1 
     and prior x = x
     and prior sys_guid() is not null
), tab3 as
(
select x, y  
  from tab2     
 where y like '%ab%'
    or y like '%cd%'
    or y like '%ef%'
)
select x, listagg(y,',') within group (order by y) as y 
  from tab3      
 group by x;

X   Y
1   ab
2   ab,cd
3   cd,ef
4   ab,ef
5   ef

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

Follow comments written within the code.

SQL> with test (x, y) as
  2    -- your sample table
  3    (select 1, 'ab' from dual union all
  4     select 2, 'ab,cd' from dual union all
  5     select 3, 'cd,ef' from dual union all
  6     select 4, 'ab,ef,gh,yu' from dual union all
  7     select 5, 'de,ef,rt' from dual
  8    ),
  9  srch (val) as
 10    -- a search string, which is to be compared to the sample table's Y column values
 11    (select 'ab,cd,ef' from dual),
 12  --
 13  srch_rows as
 14    -- split search string into rows
 15    (select regexp_substr(val, '[^,]+', 1, level) val
 16     from srch
 17     connect by level <= regexp_count(val, ',') + 1
 18    ),
 19  test_rows as
 20    -- split sample values into rows
 21    (select x,
 22            regexp_substr(y, '[^,]+', 1, column_value) y
 23     from test,
 24          table(cast(multiset(select level from dual
 25                              connect by level <= regexp_count(y, ',') + 1
 26                             ) as sys.odcinumberlist))
 27    )
 28  -- the final result
 29  select t.x, listagg(t.y, ',') within group (order by t.y) result
 30  from test_rows t join srch_rows s on s.val = t.y
 31  group by t.x
 32  order by t.x;

         X RESULT
---------- --------------------
         1 ab
         2 ab,cd
         3 cd,ef
         4 ab,ef
         5 ef

SQL>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.