sql有两个表,如何计算每个学生的单科成绩、平均成绩和总成绩

student表
id name
1 张三
2 李四
3 王五

score表
id subject score
1 math 80
1 english 90
2 math 81
2 english 91
3 math 85
3 english 95

要求得到的组合查询结果
id math english sum
1 80 90 170
2 81 91 172
3 85 95 180
avg 82 92 174


那sql应该怎么写呢?
感觉难点在于如何把math和english变成列号,以及最后一行计算出平均值?
全部评论
根据id进行关联查询
点赞 回复 分享
发布于 2016-05-15 19:54
select * from student where name='?'; 获得id 和名字 select * from score where id='?'; 得到所有的成绩,然后计算。。。 然后输出。。。 如果要存 insert into 表名 values(id,成绩,成绩,成绩); 最后一行你在程序中计算了在存入语句同上。
点赞 回复 分享
发布于 2016-05-28 22:46
先内连接查询,再计算平均值,然后再union一下
点赞 回复 分享
发布于 2016-05-29 11:35
补充cxxbro的答案 select s1.id as id,s1.score as math,s2.score as english,s1.score+s2.score as sum from student as stu join score as s1 join score as s2 where stu.id=s1.id AND s1.id=s2.id AND s1.subject='math' AND s2.subject='english' union select 'avg' as id,avg(s1.score) as math,avg(s2.score) as english,avg(s1.score+s2.score) from score as s1 join score as s2
点赞 回复 分享
发布于 2016-08-08 22:22
( SELECT stuid as id, CAST(sum(case when `subject`='math' then score end) AS SIGNED) as math, CAST(sum(case when `subject`='english' then score end) AS SIGNED) as english, CAST(( sum(case when `subject`='math' then score end) + sum(case when `subject`='english' then score end) ) AS SIGNED) as 'sum' FROM score GROUP BY stuid ) UNION ( SELECT 'avg' as id, CAST(avg(case when `subject`='math' then score end) AS SIGNED) as math, CAST(avg(case when `subject`='english' then score end) AS SIGNED) as english, CAST(( avg(case when `subject`='math' then score end) + avg(case when `subject`='english' then score end) ) AS SIGNED) as 'sum' FROM score )
点赞 回复 分享
发布于 2016-10-08 18:50

相关推荐

铁锈不腻玩家:下面那个袁先生删了,问他怎么回事,头像都换不明白
点赞 评论 收藏
分享
白菜小丑呜呜:Radis写错了兄弟
点赞 评论 收藏
分享
评论
点赞
7
分享
牛客网
牛客企业服务