ITPub博客

首页 > IT基础架构 > 网络安全 > 网友问题摘抄,不定列转换

网友问题摘抄,不定列转换

原创 网络安全 作者:cosio 时间:2008-07-28 08:39:01 0 删除 编辑

举例如下--------

表1内容:
ENFIELD CHNAME
A 序号1
B 序号2
C 序号3
D 序号4
E 序号5
... ...

------------

表2内容:
A B C D E ......
值1 值2 值3 值4 值5 ......

------------

要求SQL查询得到如下效果:把表2中的一行数据,作为表1新增的一列(VALUES)显示出来。

ENFIELD CHNAME VALUES
A 序号1 值1
B 序号2 值2
C 序号3 值3
D 序号4 值4
E 序号5 值5
... ... ...

----------------------

SQL> select * from table1;

ENFIELD CHNAME
------- ----------A id1
B id2
C id3
D id4
E id5

SQL
> select * from table2;

A B C D E
---------- ---------- ---------- ---------- ----------value1 value2 value3 value4 value5

SQL
>
SQL
> select t1.ENFIELD, t1.CHNAME, tt2.cols_values
2 from table1 t1,
3 (select substr(',' || cols || ',',
4 instr(',' || cols || ',', ',', 1, 2 * rn - 1) + 1,
5 instr(',' || cols || ',', ',', 1, 2 * rn - 1 + 1) -
6 instr(',' || cols || ',', ',', 1, 2 * rn - 1) - 1) as new_cols,
7 substr(',' || cols || ',',
8 instr(',' || cols || ',', ',', 1, 2 * rn) + 1,
9 instr(',' || cols || ',', ',', 1, 2 * rn + 1) -
10 instr(',' || cols || ',', ',', 1, 2 * rn) - 1) as cols_values
11 from (select rownum rn from all_objects where rownum <= 21) ao,
12 (select 'A' || ',' || A || ',' || 'B' || ',' || B || ',' || 'C' || ',' || C || ',' || 'D' || ',' || D || ',' || 'E' || ',' || E as cols
13 from table2) t2
14 where instr(',' || cols, ',', 1, 2 * rn - 1) > 0) tt2
15 where t1.ENFIELD = tt2.new_cols;

ENFIELD CHNAME COLS_VALUES
------- ---------- ------------------------------------------------------------------A id1 value1
B id2 value2
C id3 value3
D id4 value4
E id5 value5

[@more@]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/101162/viewspace-1007954/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: oracle面试题
请登录后发表评论 登录
全部评论

注册时间:2008-07-13

  • 博文量
    71
  • 访问量
    976099