一、unpivot函数语法
说明:将表中多个列缩减为一个聚合列(多列转多行)
语法:unpivot(新列名 for 聚合列名 in (对应的列名1…列名n ))
二、实例应用
1、unpivot的简单应用:
SELECT STU_NAME, TERM, subject, score
FROM (SELECT '罗飞' STU_NAME,
'2001-2002' TERM,
'90' 微积分,
'88' 线性代数,
'85' 数据结构,
'70' 操作系统
FROM DUAL) UNPIVOT(score FOR subject IN(微积分,
线性代数,
数据结构,
操作系统))
SELECT STU_NAME, TERM, subject, score
FROM (SELECT '罗飞' STU_NAME,
'2001-2002' TERM,
'90' 微积分,
'88' 线性代数,
'85' 数据结构,
'70' 操作系统
FROM DUAL) UNPIVOT(score FOR subject IN(微积分 as 'wjf',
线性代数 as 'xxds',
数据结构 as 'sjjg',
操作系统 as 'czxt'))
order by score
with 排名表 as
(select a.*
,dense_rank() over(order by chinese desc) chinese_rank
,dense_rank() over(order by math desc) math_rank
from (select 'A' as name ,36 chinese, 67 math from dual
union all
select 'B' as name ,56 chinese, 47 math from dual
union all
select 'C' as name ,78 chinese, 58 math from dual
union all
select 'D' as name ,53 chinese, 96 math from dual
union all
select 'E' as name ,87 chinese, 63 math from dual
) a
order by name
)
select name,学科,成绩,排名
from 排名表
unpivot
( (成绩,排名) for 学科 in ((chinese,chinese_rank) as '语文',
(math ,math_rank ) as '数学')
)
order by name
1)原数据
三、参考资料
1、ORACLE中一个简单的UNPIVOT例子
2、Oracle函数——列转行功能unpivot使用的简单举例