编程萌新,因为遇到这么个SQL 查询的问题:在一张表A里有如下字段:学生姓名、学科名、学科成绩。写一条SQL 语句查出各科平均成绩并按学生姓名分组,按如下格式显示:学生姓名|语文|数学|英语。一开始遇到的时候挺懵的,有印象但是却忘了怎么写了,接下来就是查阅资料并亲自上手测试是否可行~
第一次代码修修改改如下,此时还是在只用一张表来查询(无法实现上述目标结果,贴图只是为了说明下思考路线):
1 select UName,
2 (select AVG(Grades) from UserInfo where GName = '语文') as '语文',
3 (select AVG(Grades) from UserInfo where GName = '数学') as '数学',
4 (select AVG(Grades) from UserInfo where GName = '英语') as '英语'
5 from UserInfo
6 where UName = '小明'
7 group by UName
8 /*having GName = '语文' and GName = '数学' and GName = '英语'*/
9 order by AVG(Grades)
10 go
然后查阅资料也没有头绪,就想只用一张表是否真的可行,要不用两张表试一下?接下来就是在原表A(实际为如下代码中 UserInfo表)基础上插入一个 学生id 的字段,然后新建一张学生表(T_User),拥有两个字段:id、姓名,学生表的id匹配表A里的学生id,查询语句通过连接实现(因为是思考一个问题,就不考虑内外或者交叉连接的问题了),代码如下:
1 select UName,
2 (select AVG(Grades) from UserInfo where GName = '语文' and UName = tu.name) as '语文',
3 (select AVG(Grades) from UserInfo where GName = '数学' and UName = tu.name) as '数学',
4 (select AVG(Grades) from UserInfo where GName = '英语' and UName = tu.name) as '英语'
5 from UserInfo as ui join T_User as tu
6 on ui.UName = tu.name
7 group by ui.UName,tu.name
8 go
运行测试如下:
成功!研究并解决差不多花了1个多小时,可能资质不行,但是会继续努力。从简单入手,从萌新出发~