How to transpose column into row in oracle sql 11G

眉间皱痕 提交于 2019-12-29 09:16:09

问题


I need to convert column into row for the below select column_name from all_tab_cols where table_name='TABLE_NAME' ;

COLUMN_1
COLUMN_2
COLUMN_3
COLUMN_4
COLUMN_5
COLUMN_6
COLUMN_7

Tried using pivot operator/clause ,

i need to mention all the column names for the table if the table contain more number of column it wouldnt be possible to mention in the pivot function in in clause,

select * from
(
    select column_name
    from all_tab_cols
    where table_name = 'TABLE_NAME'
)
pivot ( min(column_name) for column_name in 
(
'COLUMN_1', 'COLUMN_2', 'COLUMN_3', 'COLUMN_4', 'COLUMN_5', 'COLUMN_6', 'COLUMN_7'
));

Expected output:

COLUMN_1    COLUMN_2    COLUMN_3    COLUMN_4    COLUMN_5    COLUMN_6    COLUMN_7

Could anyone Please advise how to convert column into rows


回答1:


Try this:

select listagg(A,'  ') within group (order by A) as Names
from test

In ur case the query goes like:

select listagg(column_name,'  ')  within group (order by column_name) as column_name
from all_tab_cols 
where table_name='TABLE_NAME' ;



回答2:


after so much time on googling

i found that pivot query haven't any dynamic features

so after i found solution at here

https://technology.amis.nl/2006/05/24/dynamic-sql-pivoting-stealing-antons-thunder/

here download pivot function from here

http://paste.ubuntu.com/21378705/

run this script and this script automatically create pivot function

with the use of this function we can create dynamic column from rows.

Example :

    select * from table( pivot(  Q'$ select column_name,column_name name 
    from all_tab_cols where table_name = 'TABLE_NAME' $') )

i hope this will help.



来源:https://stackoverflow.com/questions/38651147/how-to-transpose-column-into-row-in-oracle-sql-11g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!