如何在oracle

时间:2018-04-12 05:04:40

标签: sql oracle pivot

我正在尝试将列标题和相应字段插入另一个表中。

Table1 :

col1    col2   col3   col4
1       2       3      4

输出应如下所示:

COL_A   COL_B   COL_C     COL_D    COL_E     COL_F      COL_G    COL_H 
col1    1       col2       2       col3       3         col4     4       

我尝试应用unpivot,但是unpivot给我的列名垂直不是水平的。

2 个答案:

答案 0 :(得分:2)

试试这个。根据需要从此结果中添加适当的别名。

SELECT * FROM
 (
    SELECT *
    FROM Table1
    UNPIVOT(val FOR col IN (
                COL1
                ,COL2
                ,COL3
                ,COL4
                ))
    )
PIVOT(  MAX(COl) as C, MAX(VAL) as V FOR COL IN (
             'COL1' as VAL1
            ,'COL2' as VAL2
            ,'COL3' as VAL3
            ,'COL4' as VAL4
            ));

Demo

答案 1 :(得分:1)

这不是你想做的吗?

select 'col1' as col_a, col1 as col_b,
       'col2' as col_c, col2 as col_d,
       'col3' as col_e, col3 as col_f,
       'col4' as col_g, col4 as col_h
from t;