MYSQL横表变竖表
原始数据
目标数据
方法一:SQL语句:
select name as '姓名', max(case subject when '语文' then result else 0 end) '语文', max(case subject when '数学' then result else 0 end) '数学', max(case subject when '英语' then result else 0 end) '英语' from student group by name;
如果是汇总,语句中max换sum
精华解析:
max(case subject when '语文' then result else 0 end)
如果subject字段='语文',那么读取 result字段,否则就是0,然后再MAX一下,就取到有成绩的值了。可以用汇总统计
方法二(笨方法,硬拼):SQL语句:
select s.name as '姓名', s1.result as '语文', s2.result as '数学', s3.result as '英语' from student s left join student s1 on s1.name=s.name and subject='语文' left join student s2 on s2.name=s.name and subject='数学' left join student s3 on s3.name=s.name and subject='英语' ;