【MySQL刷题笔记】行转列,列转行

假设有如下的表:

需要转换成下面这个样子:
select student_id,
max(case project when 'Math' then grade end)Math,
max(case project when 'English' then grade end)English,
max(case project when 'Chinese' then grade end)Chinese 
from grades group by student_id;

如果有空记录,例如有个student_id为4的学生没有数学成绩的话,可以使用else填补空缺:

select student_id,
max(case project when 'Math' then grade else null end)Math,
max(case project when 'English' then grade else null end)English,
max(case project when 'Chinese' then grade else null end)Chinese 
from grades group by student_id;

显示的结果为:

发布了390 篇原创文章 · 获赞 27 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/104311855