2020-06-13
阅读量:
2689
SQL找出0611班所有男生的成绩:姓名、语文、数学、英语、物理、化学、总分,代码哪里出错了
代码:

完整代码: select stu_name,
ifnull(sum(lesson_name="语文")*score,0) 语文,
ifnull(sum(lesson_name="数学")*score,0) 数学,
ifnull(sum(lesson_name="英语")*score,0) 英语,
ifnull(sum(lesson_name="物理")*score,0) 物理,
ifnull(sum(lesson_name="化学")*score,0) 化学,
sum(score) 总分
from (select stu_id,stu_name,lesson_name,lesson_id
from t_stu_profile,t_lesson
where class_id='0611' and gender="M") t
left join t_score
on t.stu_id=t_score.stu_id and t.lesson_id=t_score.lesson_id;
图表:

代码修改如下:

第一处改成内连接,第二处加group by stu_name。
左边是笛卡尔积,遍历了所有情况,比如张三和所有课程拼接, 但是张三没有学所有的课,只是学了部分,最后用内连接把没学过的课程去掉,
另外这种写法我个人不太建议用,一个是逻辑复杂,另外计算量比较大,如果数据有很多,速度会慢。
推荐使用下面这个方法:







评论(1)

liuyong2730
2020-06-13
这么写感觉更简洁:
select stu_name,
ifnull(sum(lesson_name="语文")*score,0) 语文,
ifnull(sum(lesson_name="数学")*score,0) 数学,
ifnull(sum(lesson_name="英语")*score,0) 英语,
ifnull(sum(lesson_name="物理")*score,0) 物理,
ifnull(sum(lesson_name="化学")*score,0) 化学,
sum(score) 总分
from t_stu_profile right join t_score left join t_lesson
on t_score.lesson_id = t_lesson.lesson_id
on t_score.stu_id = t_stu_profile.stu_id
where class_id='0611' and gender="M"
group by stu_name;
20.1335
1
0
推荐帖子
0条评论
0条评论
0条评论