一、行转列
1、建表
create table table01(
sname varchar2(10), --姓名
subject varchar2(10), --科目
score int --分数
);
2、表中数据如下图显示
3、行转列转换代码
方式一(简单):
select * from table01 pivot ( sum(score) for subject in ('语文','数学','英语') );
方式二(麻烦):
select sname,
sum(case when subject='语文' then score else null end)as 语文,
sum(case when subject='数学' then score else null end)as 数学,
sum(case when subject='英语' then score else null end)as 英语
from table01
group by sname;
pivot用法:
pivot ( sum(金额、分数、数量等存放指标值的列) for 需要转换的列 in (需要转换的列中所存在的不同种类的值) );
4、行转列如下图显示
二、列转行
1、建表
create table table02(
sname varchar2(10), --姓名
语文 int, --语文科目
数学 int, --数学科目
英语 int --英语科目
);
2、表中数据如下图所示
3、列转行转换代码
方式一(简单):
select * from table02 unpivot ( score for subject in (语文,数学,英语))
方式二(麻烦):
select sname,
'语文' subject,
sum(语文) as score
from table02 group by sname
union all
select sname,
'数学' subject,
sum(数学) as score
from table02 group by sname
union all
select sname,
'英语' subject,
sum(英语) as score
from table02 group by sname
order by sname;
unpivot用法:
for 后面的subject是转换后的列,存储的是需要转换的列名(语文,数学,英语)
in 后面是subject列中存储的值(语文,数学,英语)
score 转换后的列,对应的是转换前列名(语文,数学,英语)的值
4、列转行如下图所示