1、行转列

SELECT WM_CONCAT(COLUMN_NAME) COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'T_CREATE_TABLE_1'
SELECT LISTAGG(COLUMN_NAME,';') WITHIN GROUP(ORDER BY COLUMN_NAME) COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'T_CREATE_TABLE_1'

Oracle行转列,列转行,行列相互转换-LMLPHP

注:WM_CONCAT是未公开的函数,在10.2.0.5上,其返回类型从varchar2变为了clob,而在12c当中,已经取消了此函数,所以最好别用

LISTAGG(XXX,XXX) WITHIN GROUP( ORDER BY XXX),用法就像聚合函数一样,通过Group by语句,把每个Group的一个字段,拼接起来

上面2个行数是把行用符号拼接成一列;还有PIVOT行数,可以把行转成多列

SELECT * FROM T_CREATE_TABLE_1 PIVOT (MAX(COLUMN_1) FOR COLUMN_5 IN ('列1','列2','列3'));

Oracle行转列,列转行,行列相互转换-LMLPHP

2、列转行

SELECT COLUMN_ID,COLUMN_NAME,COLUMN_DATA FROM T_CREATE_TABLE_1 UNPIVOT (COLUMN_DATA FOR COLUMN_NAME IN (COLUMN_1,COLUMN_5));

Oracle行转列,列转行,行列相互转换-LMLPHP

Oracle行转列,列转行,行列相互转换-LMLPHP

注:转换的列必须数据类型一致

05-14 17:02