首先介绍行转换为列,
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
执行语句如下:
Select student,
sum(decode(subject,'语文',grade,null)) "语文",
sum(decode(subject,'数学',grade,null)) "数学",
sum(decode(subject,'英语',grade,null)) "英语"
from grades
group by student order by student;
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方法(这种方法会随着字段的增多,变得很长,不推荐)
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',proc3
from testjac where id=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():
select A.id,B.column_name,decode(B.column_name,'PROC1',A.proc1,'PROC2',A.proc2,'PROC3',A.proc3,null) value
from test A,(select column_name from user_tab_cols where column_id>1 and table_name='TEST') B