常見sql查詢問題

https://zhuanlan.zhihu.com/p/38354000

  • student表
    *

  • teacher 表
    *

  • course 表
    *

  • score 表
    *

  1. 查詢姓“猴”的學生名單在這裏插入圖片描述

  2. 查詢姓“孟”老師的個數
    在這裏插入圖片描述

  3. 查詢課程編號爲“0002”的總成績
    4.

  4. 查詢選了課程的學生人數在這裏插入圖片描述

  5. 查詢各科成績最高和最低的分, 以如下的形式顯示:課程號,最高分,最低分在這裏插入圖片描述

  6. 查詢每門課程被選修的學生數在這裏插入圖片描述

  7. 查詢男生、女生人數在這裏插入圖片描述

  8. 查詢平均成績大於60分學生的學號和平均成績在這裏插入圖片描述

  9. 查詢至少選修兩門課程的學生學號在這裏插入圖片描述

  10. 查詢同名同性學生名單並統計同名人數在這裏插入圖片描述

  11. 查詢不及格的課程並按課程號從大到小排列在這裏插入圖片描述

  12. 查詢每門課程的平均成績,結果按平均成績升序排序,平均成績相同時,按課程號降序排列在這裏插入圖片描述

  13. 檢索課程編號爲“0004”且分數小於60的學生學號,結果按按分數降序排列在這裏插入圖片描述

  14. 統計每門課程的學生選修人數(超過2人的課程才統計)
    select 課程號, count(學號) as '選修人數' from score group by 課程號 having count(學號)>2 order by count(學號) desc,課程號 asc;

  15. 查詢兩門以上不及格課程的同學的學號及其平均成績select 學號, avg(成績) as 平均成績 from score where 成績 <60 group by 學號 having count(課程號)>=2;

  16. 查詢所有課程成績小於60分學生的學號、姓名
    select distinct(s.學號),t.姓名 from score s inner join student t on s.學號=t.學號 where s.成績 < 85;在這裏插入圖片描述
    select 學號,姓名 from student where 學號 in ( select 學號 from score where 成績 < 85 );

  17. 查詢沒有學全所有課的學生的學號、姓名|
    select 學號,姓名 from student where 學號 in(select 學號 from score group by 學號 having count(課程號)<(select count(課程號) from course));在這裏插入圖片描述

  18. 查詢出只選修了兩門課程的全部學生的學號和姓名|在這裏插入圖片描述

  19. 查找1990年出生的學生名單在這裏插入圖片描述

  20. 查詢所有學生的學號、姓名、選課數、總成績
    21.

  21. 查詢平均成績大於85的所有學生的學號、姓名和平均成績
    select a.學號,a.姓名, avg(b.成績) as 平均成績 from student as a left join score as b on a.學號 = b.學號 group by a.學號 having avg(b.成績)>85;

  22. 查詢學生的選課情況:學號,姓名,課程號,課程名稱
    select a.學號, a.姓名, c.課程號,c.課程名稱 from student a inner join score b on a.學號=b.學號 inner join course c on b.課程號=c.課程號;

  23. 查詢出每門課程的及格人數和不及格人數
    select 課程號, sum(case when 成績>=85 then 1 else 0 end) as 及格的, sum(case when 成績<85 then 1 else 0 end) as 不及格的 from score group by 課程號;
    在這裏插入圖片描述

  24. 使用分段[100-85],[85-70],[70-60],[<60]來統計各科成績,分別統計:各分數段人數,課程號和課程名稱
    25.

  25. 查詢課程編號爲0003且課程成績在80分以上的學生的學號和姓名|
    select a.學號,a.姓名 from student as a inner join score as b on a.學號=b.學號 where b.課程號='0003' and b.成績>80;

  26. 按課程號分組取成績最大值所在行的數據
    我們可以使用分組(group by)和彙總函數得到每個組裏的一個值(最大值,最小值,平均值等)。但是無法得到成績最大值所在行的數據。
    select 課程號,max(成績) as 最大成績 from score group by 課程號;在這裏插入圖片描述我們可以使用關聯子查詢來實現:select * from score as a where 成績 = ( select max(成績) from score as b where b.課程號 = a.課程號);在這裏插入圖片描述

  27. 按課程號分組取成績最小值所在行的數據
    select * from score as a where 成績 = ( select min(成績) from score as b where b.課程號 = a.課程號);在這裏插入圖片描述

  28. 查詢各科成績前兩名的記錄
    (select * from score where 課程號 = '0001' order by 成績 desc limit 2) union all (select * from score where 課程號 = '0002' order by 成績 desc limit 2) union all (select * from score where 課程號 = '0003' order by 成績 desc limit 2);在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章