You are on page 1of 2

Here are my details.

Create table input(id number,attr1 varchar2(10),attr2 varchar2(10),attr3


varchar2(10));
Insert into input values(1,’,100,’,’,101,102,’,null);

Create table lookup(code number, meaning varchar2(10));


Insert into lookup values(100,’APPLE’);
Insert into lookup values(101,’ORANGE’);
Insert into lookup values(102,’PEARS’);
Commit;

Input:

ID ATTR1 ATTR2 ATTR3


1 ,100, ,101,102 NULL

Lookup:

CODE MEANING
100 APPLE
101 ORANGE
102 PEARS

Output:

ID ATTR1 ATTR2 ATTR3


1 APPLE ORANGE;PEARS NULL

Input ID needs to lookup on the CODE column in the Lookup table.


Tricky part is having multiple comma separated values in the column and it starts
with comm (,) and ends with (,) that needs to be ignored
I used SUBSTR and INSTR to ignore the comma and pretty much able to do with a
single value but got struck with multi value.

select inp.*,
(
select listagg(lok.meaning, ';') within group (order by 1)
from
(
select
regexp_substr(inp.attr2,'[^,]+', 1, level) as the_values
from dual
connect by level <= regexp_count(inp.attr2, ',')
) inp, lookup lok
where inp.the_values = lok.code
) as decoded_value1
from input inp;

ID ATTR1 ATTR2 ATTR3 DECODED_VALUE1


---------- ---------- ---------- -------- --------
1 ,100, ,101,102, ORANGE;PEARS

---------------------------------------------------------------
Cheers,
select inp.*,
(
select listagg(lok.meaning, ';') within group (order by 1)
from
(
select
regexp_substr(inp.attr2,'[^,]+', 1, level) as the_values
from dual
connect by level <= regexp_count(inp.attr2, ',')
) inp, lookup lok
where inp.the_values = lok.code
) as decoded_value1
from input inp;

ID ATTR1 ATTR2 ATTR3 DECODED_VALUE1


---------- ---------- ---------- -------- --------
1 ,100, ,101,102, ORANGE;PEARS

-----------------------------------------------------------------------------------
-
WITH got_meaning AS
(
SELECT u.id, u.col
, l.meaning
FROM input
UNPIVOT INCLUDE NULLS
( str
FOR col IN (attr1, attr2, attr3)
) u
LEFT JOIN lookup l ON INSTR ( u.str
, ',' || l.code || ','
) > 0
)
SELECT *
FROM got_meaning
PIVOT ( LISTAGG (meaning, ';')
WITHIN GROUP (ORDER BY meaning)
FOR col IN ( 'ATTR1' AS attr1
, 'ATTR2' AS attr2
, 'ATTR3' AS attr3
)
)
ORDER BY id
;
Output from your sample data:
ID ATTR1 ATTR2 ATTR3
---------- -------------------- -------------------- --------------------
1 APPLE ORANGE;PEARS

You might also like