您的位置:首页 > 数据库

查询每个学生的各科成绩sql语句

2016-03-22 16:22 786 查看
数据库中有三个表 Student , Course, Grade 分别表示 学生, 课程,成绩
表的结构如下:  Student( studentId, name, sex)  分别表示: 学号,姓名, 性别
Course ( cid , cname)  分别表示: 课程号,课程名
Grade ( gid, studentId , cid, score) 分别表示: 成绩编号, 学号, 课程号, 成绩

现在要查询每个学生的各科成绩和平均分
查询结果打印出的样式如下:

序号        姓名         性别            语文          数学         英语         哲学            平均成绩
1             王五         男                80            70             80            90                 80
2             李明         女               90             70              70           80                77.5

列名 语文, 数学,   英语, 哲学 是 Course 中的课程名, 查询出的样式一定要与上面的一样,(假设 Course 表中 cname 只有四个  语文, 数学, 英语, 哲学)
select a.studentId,a.name,a.sex,c.cid,b.cname,c.score
into TableA
from Student a, Course b, Grade c
where a.studentId=c.studentId and c.cid=b.cid

select a.studentId,a.name,a.sex,
sum(case cname when "语文" then score else 0 end) as 语文,
sum(case cname when "数学" then score else 0 end) as 数学,
sum(case cname when "英语" then score else 0 end) as 英语,
sum(case cname when "哲学" then score else 0 end) as 哲学,
sum(score)*1.0/4 as "平均成绩"
from TableA
group by name
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: