等同于Excel索引匹配的Oracle SQL

时间:2019-01-14 19:39:05

标签: sql oracle

我想了解如何使用ORACLE SQL代码来模仿Index and Match在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

目标:

用表2中的Age替换HeightMeaning的值

预期结果:

cid  Name  Age           Height
001  Mary  40 years old  5'2 
002  Cat   22 years old  5'4

在Excel中执行此操作的当前方法:

EXCEL PROCESS

我如何在Oracle中做同样的事情?

1 个答案:

答案 0 :(得分:1)

您可以从table_1table_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

使用CTE中的样本数据:

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