Here's one way to approach this:
Join the two tables where:
- The AGE column = the code in T2 AND T2 field type is Age
OR
- The HEIGHT column = the code in T2 AND T2 field type is Height
e.g.:
select *
from table_1 t1
join table_2 t2
on ( t1.age = t2.code and t2.dfield = 'Age' ) or
( t1.height = t2.code and t2.dfield = 'Height' );
CID CNAME AGE HEIGHT DFIELD CODE MEANING
001 Mary E40 E22 Height E22 5"2
001 Mary E40 E22 Age E40 40 years old
002 Cat E22 E40 Height E40 5"4
002 Cat E22 E40 Age E22 22 years old
This gives you a row/column in t1 you've joined to t2. To collapse these back into one, pivot the results:
with rws as (
select cid, cname, dfield, meaning
from table_1 t1
join table_2 t2
on ( t1.age = t2.code and t2.dfield = 'Age' ) or
( t1.height = t2.code and t2.dfield = 'Height' )
)
select * from rws
pivot (
max ( meaning ) for
dfield in (
'Age' age, 'Height' height
)
)
order by 1;
CID CNAME AGE HEIGHT
001 Mary 40 years old 5"2
002 Cat 22 years old 5"4
Here's the create table + inserts:
create table table_1 (
cid varchar(25),
cname varchar(25),
age varchar(25),
height varchar(25)
);
create table table_2 (
dfield varchar(25),
code varchar(25),
meaning varchar(25)
);
insert into table_1 values ('001', 'Mary', 'E40', 'E22');
insert into table_1 values ('002', 'Cat', 'E22', 'E40') ;
insert into table_2 values ('Height', 'E22', '5"2');
insert into table_2 values ('Height', 'E40', '5"4') ;
insert into table_2 values ('Age','E40','40 years old') ;
insert into table_2 values ('Age', 'E22', '22 years old') ;