Oracle、mysql经典例题二--如何把学生成绩竖着排列
本例题是基于 Oracle、mysql经典例题一(如何把表格数据竖着排列)题目升级的,没看过之前的可能会有些疑惑。
题目:3张表
Student表
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/eab6b033cdc177876b2d6be46f734469.png)
Course表
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6f2764a0240259706036bf8ab5c60026.png)
Score表
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/458b0660499914209600fa2c3bf5a06a.png)
如何把这3张表合成下图形式?
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9d981440f45b4af0cebd42f76e1f6c6b.png)
解决:
第一种:简单暴力的
SELECT 姓名,SUM(语文),SUM(数学),SUM(英语),SUM(历史) FROM(
SELECT studentName AS 姓名,score AS 语文,0 AS 数学,0 AS 英语,0 AS 历史 from Student st,Course co,Score sc where st.studentid=sc.studentid and co.CourseId=sc.CourseId
group by StudentName,score,sc.courseId having sc.CourseId='1'
UNION ALL
SELECT studentName AS 姓名,0 AS 语文,score AS 数学,0 AS 英语,0 AS 历史 from Student st,Course co,Score sc where st.studentid=sc.studentid and co.CourseId=sc.CourseId
group by StudentName,score,sc.courseId having sc.CourseId='2'
UNION ALL
SELECT studentName AS 姓名,0 AS 语文,0 AS 数学,score AS 英语,0 AS 历史 from Student st,Course co,Score sc where st.studentid=sc.studentid and co.CourseId=sc.CourseId
group by StudentName,score,sc.courseId having sc.CourseId='3'
UNION ALL
SELECT studentName AS 姓名,0 AS 语文,0 AS 数学,0 AS 英语,score AS 历史 from Student st,Course co,Score sc where st.studentid=sc.studentid and co.CourseId=sc.CourseId
group by StudentName,score,sc.courseId having sc.CourseId=