列转行
unpivot函数:
- unpivot是一种列转行函数,可以将指定字段的列转换为行
- 可以通过将unpivot接在查询结果集的后面来实现对结果集的处理
unpivot函数用法:
unpivot(new_结果列 for new_维度列 in (column1 as 维值1,column2 as 维值1,……))
--源表数据
select * from student_score1
select class,id,name,subject,score
from student_score1
unpivot(score for subject in (chinese as '语文',math as '数学',english as '英语'))
行转列
原表数据
方法1:pivot函数
- pivot函数是一种行转列函数,可以将指定字段的值转换为列
- 可以通过将unpivot接在查询结果集的后面来实现对结果集的处理
pivot函数用法:
pivot (聚合函数(取值列) for 维度列 in ((维值1 as 列1,维值2 as 列2,……))
select class,id,name,chinese,math,english
from student_score2
pivot(max(score) for subject in ('语文' as chinese,'数学' as math,'英语' as english))
order by class
方法2:case……when……做条件取值判断
语法1:
case 条件
when 值1 then 返回值1
when 值2 then 返回值2
when 值3 then 返回值3
……
else 返回值n
end
语法2:
case when 条件1 then 返回值1
when 条件2 then 返回值2
when 条件3 then 返回值3
when 条件4 then 返回值4
……
else 返回值n
end
select class,id,name,
sum(case when subject = '语文' then score else 0 end) chinese,
sum(case when subject = '数学' then score else 0 end) math,
sum(case when subject = '英语' then score else 0 end) english
from student_score2
group by class,id,name
order by id
;
方法3:decode函数
对给定条件进行判断,如果条件值为指1,则得到返回值1,若条件值为指2,得到返回值2,以此类推,若条件值不满足所有给定值,则返回最后给定的一个缺省值
decode函数用法:
decode(条件,值1,返回值1,值2,返回值2,……,缺省值)
select class,id,name,
sum(decode(subject,'语文',score,0)) chinese,
sum(decode(subject,'数学',score,0)) chinese,
sum(decode(subject,'英语',score,0)) chinese
from student_score2
group by class,id,name
order by id
;