1.pivot函数
PIVOT(任意聚合函数 FOR 列名 IN(类型))
其中,【聚合函数】聚合的字段,是需要转化为列值的字段;【列名】是需要转化为列标识的字段,【类型】即是需要的结果展示,【类型】中可以指定别名; IN中还可以指定子查询。
案例:
select * from (select name,subject,score from stu_tmp)
pivot(sum(score) for subject in ('语文' ,'数学' as math,'英语','物理'));
2.unpivot函数
UNPIVOT(自定义列名1【存放转换前列的值】 FOR 自定义列名2【转换后列名,存放转换前的列名】 IN(【转换前列名】))
案例:
3.pivot函数可以替换的方案有2个
3.1使用max和decode替换
select name,
max(decode(subject,'语文',score,0)) as lan,
max(decode(subject,'数学',score,0)) as mat,
max(decode(subject,'英语',score,0)) as eng,
max(decode(subject,'物理',score,0)) as phy
from stu_tmp
group by name;
3.2使用case when,group by替换
select name,
sum(case when subject='语文' then score else 0 end) as lan,
sum(case when subject='数学' then score else 0 end) as mat,
sum(case when subject='英语' then score else 0 end) as eng,
sum(case when subject='物理' then score else 0 end) as phy
from stu_tmp
group by name;