【问题标题】:How to include column names along with rows in a result set in oracle如何在 oracle 的结果集中包含列名和行
【发布时间】:2018-04-12 05:04:39
【问题描述】:

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

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 给了我垂直而不是水平的列名。

【问题讨论】:

标签: sql oracle pivot


【解决方案1】:

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

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

【讨论】:

  • 你好 Kaushik,如果我事先不知道表结构和列名应该采用什么方法
  • @joe :您可以查询表*_tab_columns 并获取列名,使用LISTAGG 将它们连接起来。从 PL/SQL 中的结果字符串动态构造查询。 google dynamic pivot/unpivot for oracle,你会得到很多结果。如果您想进行类似的练习,也可以使用 Gordon 的方法。
  • tried dynamic query here,但是不行,请看一下
  • @joe : 你应该尝试使用动态 PL/SQL
  • 嗨@Kaushik,I have edited the question with dynamic sql that I have tried,它适用于特定的表,但对于具有不同结构的表会引发一些错误。你能看看,我不确定我做错了什么。
【解决方案2】:

这不是你想要的吗?

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;

【讨论】:

  • 只有在我知道表中的列名的情况下才有效,在我的情况下,我只知道表名,我需要从 all_tab_columns 中获取列名,我仍然不确定我会怎么做它是动态的(事先不知道列名)
  • 我可以这样做,如果我事先知道表结构.. select (select column_name from all_tab_columns where COLUMN_ID =1 and table_name = 'TEST1') , col1 , (select column_name from all_tab_columns where COLUMN_ID = 2 and table_name = 'TEST1') , col2 , (select column_name from all_tab_columns where COLUMN_ID =3 and table_name = 'TEST1') , col3 , (select column_name from all_tab_columns where COLUMN_ID =4 and table_name = 'TEST1') , col4 from test1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多