Oracle SQL相当于Excel的索引匹配
我想了解如何使用ORACLE SQL代码来模拟在Excel中可以实现的索引和匹配 表1:Oracle SQL相当于Excel的索引匹配,sql,oracle,Sql,Oracle,我想了解如何使用ORACLE SQL代码来模拟在Excel中可以实现的索引和匹配 表1: cid Cname Age Height 001 Mary E40 E22 002 Cat E22 E40 表2: Fname CODE MEAING Age E40 40 years old Age E22 22 years old Height E22 5'2 Height E40 5'4 目标:
cid Cname Age Height
001 Mary E40 E22
002 Cat E22 E40
表2:
Fname CODE MEAING
Age E40 40 years old
Age E22 22 years old
Height E22 5'2
Height E40 5'4
目标:
将年龄
和身高
的值替换为表2中的含义
预期结果:
cid Name Age Height
001 Mary 40 years old 5'2
002 Cat 22 years old 5'4
在Excel中执行此操作的当前方式:
如何在Oracle中执行相同的操作?您可以从
表1
连接到表2
两次,每种数据点类型连接一次:
select t1.cid, t1.cname as name,
t2_age.meaing as age, t2_height.meaing as height
from table_1 t1
join table_2 t2_age on t2_age.fname = 'Age' and t2_age.code = t1.age
join table_2 t2_height on t2_height.fname = 'Height' and t2_height.code = t1.height
使用CTEs中的样本数据:
with table_1 (cid, cname, age, height) as (
select '001', 'Mary', 'E40', 'E22' from dual
union all select '002', 'Cat', 'E22', 'E40' from dual
),
table_2 (fname, code, meaing) as (
select 'Age', 'E40', '40 years old' from dual
union all select 'Age', 'E22', '22 years old' from dual
union all select 'Height', 'E22', '5''2' from dual
union all select 'Height', 'E40', '5''4' from dual
)
select t1.cid, t1.cname as name,
t2_age.meaing as age, t2_height.meaing as height
from table_1 t1
join table_2 t2_age on t2_age.fname = 'Age' and t2_age.code = t1.age
join table_2 t2_height on t2_height.fname = 'Height' and t2_height.code = t1.height;
CID NAME AGE HEIGHT
--- ---- ------------ ------------
001 Mary 40 years old 5'2
002 Cat 22 years old 5'4
或者,您可以加入一次,然后使用条件聚合来选择相关值:
select t1.cid, t1.cname as name,
max(case when t2.fname = 'Age' then t2.meaing end) as age,
max(case when t2.fname = 'Height' then t2.meaing end) as height
from table_1 t1
join table_2 t2 on (t2.fname = 'Age' and t2.code = t1.age)
or (t2.fname = 'Height' and t2.code = t1.height)
group by t1.cid, t1.cname;
CID NAME AGE HEIGHT
--- ---- ------------ ------------
001 Mary 40 years old 5'2
002 Cat 22 years old 5'4
基本上是一个手动枢轴:
select *
from (
select t1.cid, t1.cname as name, t2.fname, t2.meaing
from table_1 t1
join table_2 t2 on (t2.fname = 'Age' and t2.code = t1.age)
or (t2.fname = 'Height' and t2.code = t1.height)
)
pivot (max(meaing) for (fname) in ('Age' as age, 'Height' as height));
CID NAME AGE HEIGHT
--- ---- ------------ ------------
001 Mary 40 years old 5'2
002 Cat 22 years old 5'4