使用动态列 Oracle SQL 查询的数据
Posted
技术标签:
【中文标题】使用动态列 Oracle SQL 查询的数据【英文标题】:Data using Dynamic Column Oracle SQL query 【发布时间】:2018-07-11 04:39:11 【问题描述】:全部 - 我想在下面使用 Oracle SQL 查询(不是 PL/SQL)来实现。请让我知道它是否可以实现
表 1
Column Name : ONLY_COLUMN
Values:
COLUMN1
COLUMN5
COLUMN3
表 2
COLUMN1 COLUMN2 COLUMN3 COLUMN4 COLUMN5
V1 V2 V3 V4 V5
查询输出
(SELECT_COLUMN_VALUE_FROM_TABLE 1) (VALUE_FROM_CORRESPONDING_COLUMN_FROM_TABLE 2)
COLUMN1 V1
COLUMN5 V5
COLUMN3 V3
【问题讨论】:
【参考方案1】:只有当列列表固定时,您才能在纯 SQL 中执行此操作,就像您的情况一样。
with tbl1 as (
select 'COLUMN1' only_column from dual union all
select 'COLUMN5' only_column from dual union all
select 'COLUMN3' only_column from dual
),
tbl2 as (
select 'V1' COLUMN1, 'V2' COLUMN2, 'V3' COLUMN3, 'V4' COLUMN4,'V5' COLUMN5 from dual
)
select only_column,
case only_column
when 'COLUMN1' then COLUMN1
when 'COLUMN2' then COLUMN2
when 'COLUMN3' then COLUMN3
when 'COLUMN4' then COLUMN4
when 'COLUMN5' then COLUMN5
end res
from tbl2, tbl1
输出:
ONLY_COLUMN RES
----------
COLUMN1 V1
COLUMN5 V5
COLUMN3 V3
【讨论】:
【参考方案2】:试试这个
create table tst (col varchar2(10));
create table tst1 (c1 varchar2(10), c2 varchar2(10), c3 varchar2(10), c4 varchar2(10), c5 varchar2(10));
insert into tst values ('c1');
insert into tst values ('c5');
insert into tst values ('c3');
insert into tst1 values ('V1', 'V2', 'V3', 'V4', 'V5');
Select tst.col,
case
when tst.col = 'c1' then tst1.c1
when tst.col = 'c2' then tst1.c2
when tst.col = 'c3' then tst1.c3
when tst.col = 'c4' then tst1.c4
when tst.col = 'c5' then tst1.c5
end as val
From tst, tst1
【讨论】:
【参考方案3】:使用 unpivot,这是非常直接的:
with tbl1 as (
select 'COLUMN1' only_column from dual union all
select 'COLUMN5' only_column from dual union all
select 'COLUMN3' only_column from dual
),
tbl2 as (
select 'V1' COLUMN1, 'V2' COLUMN2, 'V3' COLUMN3, 'V4' COLUMN4,'V5' COLUMN5 from dual
),
piv2 as (
select *
from tbl2
unpivot( val for col in (COLUMN1,COLUMN2,COLUMN3,COLUMN4,COLUMN5))
)
select only_column, val from tbl1,piv2
where piv2.col = tbl1.only_column
结果:
ONLY_COLUMN VAL
----------- ---
COLUMN1 V1
COLUMN3 V3
COLUMN5 V5
【讨论】:
以上是关于使用动态列 Oracle SQL 查询的数据的主要内容,如果未能解决你的问题,请参考以下文章