mysql查詢每個學生的各科成績,以及總分和平均分


今天看一個mysql教程,看到一個例子,感覺里面的解決方案不是很合理。
問題如下:
有學生表:
在這里插入圖片描述
成績表:
在這里插入圖片描述
想要查詢出的效果:
在這里插入圖片描述

其實就是原來是一個分數一條記錄,現在變成一個學生一條記錄。
那個教程里的sql如下:

select a.id as 學號, a.name as 姓名, 
(case when b.kemu='語文' then score else 0 end) as 語文,
(case when b.kemu='數學' then score else 0 end) as 數學,
(case when b.kemu='英語' then score else 0 end) as 英語
from student a, grade b
where a.id = b.id

實現的效果:
在這里插入圖片描述
很明顯,每個學生的每個成績都是單獨一條記錄,那和原來沒有什么區別嘛。
改進后的sql如下:

SELECT s.id, s.name, 
max(case when g.kemu='語文' then score else 0 end) as 語文,
max(case when g.kemu='數學' then score else 0 end) as 數學,
max(case when g.kemu='英語' then score else 0 end) as 英語,
sum(score) as 總分,
avg(score) as 平均分
from student s LEFT JOIN grade g ON  s.id = g.s_id GROUP BY s.id

就是使用了聚合函數,效果如下:
在這里插入圖片描述
是不是比原來的效果好很多了呢


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM