一、現有以下兩張表:
第一張表名為cust,其表結構如下:
字段名 | 字段說明 | 是否主鍵 |
Studentno | 學號,數據類型為整型的 | 是 |
Name | 學生名字,數據類型為字符串型的 | 否 |
Address | 學生住址,數據類型為字符串型的 | 否 |
Telno | 電話號碼,數據類型為字符串型的 | 否 |
第二張表名為mark,其表結構如下:
字段名 | 字段說明 | 是否為主鍵 |
studentno | 學號,數據類型為整型的 | 是 |
english | 英語成績,數據類型為數字型的 | 否 |
math | 數學成績,數據類型為數字型的 | 否 |
computer | 計算機成績,數據類型為數字型的 | 否 |
1) [5分]請寫出計算 所有學生的英語平均成績的sq|語句。
SELECT a.Studentno, a. NAME, b.english FROM cust a JOIN mark b ON a.Studentno = b.studentno
2) [5分]現有五 個學生,其學號假定分別為11,22,33,44,55;請用一條SQL語句實現列出這五個學生的數學成績及其姓名、學生地址、電話號碼;
SELECT a. NAME, b.math, a.Address, a.Telno FROM cust a JOIN mark b ON a.Studentno = b.studentno WHERE a.Studentno IN (11, 22, 33, 44, 55);
3)[5分]查詢所有學生的姓名、計算機成績,按照計算機成績從高到低排序;
SELECT a. NAME, b.computer FROM cust a JOIN mark b ON a.Studentno = b.studentno ORDER BY b.computer DESC;
4)[5分]查詢所有總成績大於240分的學生學號、姓名、總成績,按照總成績從高到低排序;
SELECT a.Studentno, a. NAME, sum(b.math + b.english + b.computer) zcj FROM cust a JOIN mark b ON a.Studentno = b.studentno GROUP BY a.Studentno, a. NAME HAVING zcj > 240 ORDER BY zcj DESC;
二、
表名 | 字段 | 備注 |
student | id | 學號 |
name | 學生姓名 | |
course | id | 課程編號 |
name | 課程名稱 | |
sc | sid | 學號 |
cid | 課程編號 | |
score | 成績 |
請寫出如下SQL:
A.查詢姓‘王’的學生的個數;
select count(*) from student where name like '王%';
B. 查詢“數學”比“語文”成績高的所有學生的學號;
法一:使用case...when.. then...end語句:
select a.id,a.name, sum(case when c.name='語文' then b.score end) chinese, sum(case when c.name='數學' then b.score end) math from student a join sc b on a.id=b.sid join course c on c.id=b.cid group by a.id,a.name having math>chinese
法二:嵌套查詢的方式:
select student.id from student, (select * from sc where cid=(select id from course where name='語文')) chinese, (select * from sc where cid=(select id from course where name='數學')) math where student.id=chinese.sid and chinese.sid=math.sid and math.score>chinese.score
C.查詢平均成績大於90分的同學的學號和平均成績。
不涉及到學科的問題,只需關聯學生表和成績表即可:
SELECT a.id, a. name, avg(b.score) FROM student a JOIN sc b ON a.id = b.sid GROUP BY id, name HAVING avg(b.score) > 90;
解題思路:
第二題中,①首先,要知道的是學生的id,姓名和語數成績,查詢出來如下所示:
②用case...when...then...end語句,分別查詢出課程名為語文和數學的成績,如下圖所示:
注意:這里注意,為什么需要寫兩個case...when...then...end語句,因為我們要顯示的是兩列,實現分組功能
③去null值,用聚合函數,求和、最大值、最小值都可以
④篩選出數學成績大於語文成績的,having即可
第三題求平均成績,不涉及到課程,只需要關聯兩張表即可
三、
查詢學生信息表中男生一共有多少人
select count(*) from t_student where sex='男'
查詢男生成績中前3名的成績
SELECT b.score FROM student a JOIN sc b ON a.id = b.sid WHERE sex = '男' ORDER BY b.score DESC LIMIT 3
查詢男生成績中排名第3的成績
SELECT b.score FROM student a JOIN sc b ON a.id = b.sid WHERE sex = '男' ORDER BY b.score DESC LIMIT 2,1
如果在上一題的基礎上,若第三名的男生成績有重復的兩個
distinct去重,會把重復的去掉,只保留一個