资源描述:
《数据库列转行、行转列.doc》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、1、列转行CREATETABLEt_col_row(IDINT,c1VARCHAR2(10),c2VARCHAR2(10),c3VARCHAR2(10));INSERTINTOt_col_rowVALUES(1,'v11','v21','v31');INSERTINTOt_col_rowVALUES(2,'v12','v22',NULL);INSERTINTOt_col_rowVALUES(3,'v13',NULL,'v33');INSERTINTOt_col_rowVALUES(4,NULL,'v24','v34');INSERTINTOt_c
2、ol_rowVALUES(5,'v15',NULL,NULL);INSERTINTOt_col_rowVALUES(6,NULL,NULL,'v35');INSERTINTOt_col_rowVALUES(7,NULL,NULL,NULL);COMMIT;SELECT*FROMt_col_row;1)UNIONALL适用范围:8i,9i,10g及以后版本SELECTid,'c1'cn,c1cvFROMt_col_rowUNIONALLSELECTid,'c2'cn,c2cvFROMt_col_rowUNIONALLSELECTid,'c3'cn,
3、c3cvFROMt_col_row;若空行不需要转换,只需加一个where条件,WHERECOLUMNISNOTNULL即可。2)MODEL适用范围:10g及以后SELECTid,cn,cvFROMt_col_rowMODELRETURNUPDATEDROWSPARTITIONBY(ID)DIMENSIONBY(0ASn)MEASURES('xx'AScn,'yyy'AScv,c1,c2,c3)RULESUPSERTALL(cn[1]='c1',cn[2]='c2',cn[3]='c3',cv[1]=c1[0],cv[2]=c2[0],cv[3]
4、=c3[0])ORDERBYID,cn;3)collection适用范围:8i,9i,10g及以后版本要创建一个对象和一个集合:CREATETYPEcv_pairASOBJECT(cnVARCHAR2(10),cvVARCHAR2(10));CREATETYPEcv_varrASVARRAY(8)OFcv_pair;SELECTid,t.cnAScn,t.cvAScvFROMt_col_row,TABLE(cv_varr(cv_pair('c1',t_col_row.c1),cv_pair('c2',t_col_row.c2),cv_pair('
5、c3',t_col_row.c3)))tORDERBY1,2;2、行转列CREATETABLEt_row_colASSELECTid,'c1'cn,c1cvFROMt_col_rowUNIONALLSELECTid,'c2'cn,c2cvFROMt_col_rowUNIONALLSELECTid,'c3'cn,c3cvFROMt_col_row;SELECT*FROMt_row_colORDERBY1,2;1)AGGREGATEFUNCTION适用范围:8i,9i,10g及以后版本SELECTid,MAX(decode(cn,'c1',cv,NU
6、LL))ASc1,MAX(decode(cn,'c2',cv,NULL))ASc2,MAX(decode(cn,'c3',cv,NULL))ASc3FROMt_row_colGROUPBYidORDERBY1;MAX聚集函数也可以用sum、min、avg等其他聚集函数替代。被指定的转置列只能有一列,但固定的列可以有多列,请看下面的例子:SELECTmgr,deptno,empno,enameFROMempORDERBY1,2;SELECTmgr,deptno,MAX(decode(empno,'7788',ename,NULL))"7788",M
7、AX(decode(empno,'7902',ename,NULL))"7902",MAX(decode(empno,'7844',ename,NULL))"7844",MAX(decode(empno,'7521',ename,NULL))"7521",MAX(decode(empno,'7900',ename,NULL))"7900",MAX(decode(empno,'7499',ename,NULL))"7499",MAX(decode(empno,'7654',ename,NULL))"7654"FROMempWHEREmgrIN(75
8、66,7698)ANDdeptnoIN(20,30)GROUPBYmgr,deptnoORDERBY1,2;这里转置列为empno,固定