使用动态列Oracle SQL查询数据

时间:2018-07-11 04:39:12

标签: sql database oracle

全部-我想在下面使用Oracle SQL查询(不是PL / SQL)来实现。请让我知道它是否可以实现

表1

 Select * from tblConfig
 Cross Join tblData

表2

Column Name : ONLY_COLUMN

Values: 

COLUMN1

COLUMN5

COLUMN3

查询输出

COLUMN1 COLUMN2 COLUMN3 COLUMN4 COLUMN5

V1       V2       V3      V4      V5

COLUMN1 V1

COLUMN5 V5

COLUMN3 V3


3 个答案:

答案 0 :(得分:0)

仅当列列表固定时才可以在纯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

答案 1 :(得分:0)

尝试一下

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

答案 2 :(得分:0)

毫不费力地向前迈进:

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