Oracle 实现行转列的几种方法
表数据
with students as
(
select 99 score, 'chinese' course, 'zhangsan' name
from dual
union all
select 89 score, 'math' course, 'zhangsan' name
from dual
union all
select 97 score, 'english' course, 'zhangsan' name
from dual
union all
select 96 score, 'chinese' course, 'wangwu' name
from dual
union all
select 95 score, 'math' course, 'wangwu' name
from dual
union all
select 94 score, 'english' course, 'wangwu' name
from dual
)
select * from students
1 使用 decode 与聚合函数实现
select t.name,
sum(decode(t.course, 'chinese', score, null)) as CHINESE,
sum(decode(t.course, 'math', score, null)) as MATH,
sum(decode(t.course, 'english', score, null)) as ENGLISH
from students t
group by t.name
order by t.name
查询结果
2 使用 case when 与聚合函数实现
select t.name,
max(case when t.course = 'chinese' then t.score end) chinese,
max(case when t.course = 'math' then t.score end) math,
max(case when t.course = 'english' then t.score end) english
from students t
group by t.name
order by t.name
查询结果
3 使用 pivot 函数
select *
from
(select course, score, name from students)
pivot (max(score) -- max 里是要转的列的值
for course -- 需要转的列
in ( 'chinese' chhinese,'math' math,'english' english ))
order by name