首先介绍行转换为列,
oracle行转换为列是比较常见,网上常见的例子如下:
grades表:
student subject grade
student1 语文 80
student1 数学 70
student1 英语 60
student2 语文 90
student2 数学 80
student2 英语 10
转换为
语文 数学 英语
Student1 80 70 60
Student2 90 80 100
执行语句如下:
view plain copy to clipboard print ?
Selectstudent,
sum(decode(subject,'语文',grade,null))"语文",
sum(decode(subject,'数学',grade,null))"数学",
sum(decode(subject,'英语',grade,null))"英语"
fromgrades
groupbystudentorderbystudent; Select student,sum(decode(subject,'语文',grade,null)) "语文",sum(decode(subject,'数学',grade,null)) "数学",sum(decode(subject,'英语',grade,null)) "英语"from gradesgroup by student order by student;
下面,介绍列转换为行的操作:
假设一个表test,记录如下:
表头 id proc1 proc2 proc3
记录 12 3.4 6.7 12.4
想变成如下格式:
表头 id proc value
记录 12 proc1 3.4
记录 12 proc2 6.7
记录 12 proc3 12.4
方法一:采用union all方法(这种方法会随着字段的增多,变得很长,不推荐)
view plain copy to clipboard print ?
selectid,'proc1',proc1
fromtestjacwhereid=12
unionall
selectid,'proc2',proc2
fromtestjacwhereid=12
unionall
selectid,'proc3',proc3
fromtestjacwhereid=12; select id,'proc1',proc1 from testjac where id=12 union all select id,'proc2',proc2 from testjac where id=12 union all select id,'proc3',proc3from testjac where id=12;
方法二:采用decode+系统视图USER_TAB_COLS(推荐):
view plain copy to clipboard print ?
selectA.id,B.column_name,decode(B.column_name,'PROC1',A.proc1,'PROC2',A.proc2,'PROC3',A.proc3,null) value
fromtest A,(selectcolumn_namefromuser_tab_colswherecolumn_id>1andtable_name='TEST') B