先创建一个表出来,像下面这样子
这是一个最基本的用学生成绩来实现行转列数据。
然后我们要做的就是转换成
怎么做呢,上操作
-- 行列转换(group by + case when)
select
sname '姓名',
max(case course when '语文' then score else 0 end) as '语文',
max(case course when '数学' then score else 0 end) as '数学',
max(case course when '英语' then score else 0 end) as '英语'
from work
group by sname;
这个是使用的 case when,也可以使用if
-- 行列转换(group by + if)
select
sname '姓名',
sum(if(course='语文',score,0)) as '语文',
sum(if(course='数学',score,0)) as '数学',
sum(if(course='英语',score,0)) as '英语'
from work
group by sname;
这两种方法都可以使用,出来的数据就像,下面这样子
行转列到这里就完成了ヾ(≧▽≦*)o