初学SQL数据库,做了一些简单的SQL语句相关实验,作为学习进度更近,方便后期复习
以下是本篇文章正文内容,下面案例可供参考
表或视图数据的各种查询(与统计)SQL命令操作,具体分为:
1、了解查询的概念和方法。
2、掌握SQLServer集成管理器查询子窗口中执行SELECT操作的方法。
3、掌握SELECT语句在单表查询中的应用。
4、掌握SELECT语句在多表查询中的应用。
5、掌握SELECT语句在复杂查询中的使用方法。
1. 检索王同学不学的课程的课程号。
SELECT DISTINCT Sname
FROM Student
WHERE Ssex='女' and EXISTS(SELECT *
FROM SC
WHERE Sno=Student.Sno)
2. 检索王同学不学的课程的课程号
SELECT Cno
FROM Course
WHERE CNO NOT IN (SELECT CNO
FROM SC,STUDENT
WHERE STUDENT.SNO = SC.SNO AND STUDENT.SNAME LIKE '王%')
3.检索全部学生都选修的课程的课程号与课程名
SELECT CNO,Cname
FROM COURSE
WHERE NOT EXISTS(SELECT *
FROM Student
WHERE NOT EXISTS(SELECT *
FROM SC
WHERE SC.Sno = Student.Sno AND SC.Cno = COURSE.Cno))
4.检索选修了所有3学分课程的学生学号
SELECT SNO
FROM SC
WHERE CNO IN(SELECT CNO
FROM COURSE
WHERE CCREDIT = 3)
GROUP BY SNO
HAVING COUNT (CNO) = (SELECT COUNT(*)
FROM COURSE
WHERE CCREDIT =3)
5.统计所有(每个)学生选修的课程门数,要求显示学号和课程门数,包括没有选课的学生
SELECT STUDENT.SNO,COUNT (DISTINCT CNO)
FROM STUDENT LEFT OUTER JOIN SC ON STUDENT.SNO =SC.SNO
GROUP BY STUDENT.SNO
6.求选修课程号为4课程的学生的平均年龄。
SELECT AVG(Sage)
FROM Student
WHERE SNO IN (SELECT SNO
FROM SC
WHERE Cno = 4)
7.求学分为3的每门课程的学生平均成绩
SELECT cno,AVG(GRADE)
FROM SC
WHERE cno in (select cno
from course
where ccredit = 3)
GROUP BY cno
8.检索学号比王非同学大,而年龄比他小的学生姓名
SELECT Sname
FROM Student
WHERE Sage <(SELECT Sage
FROM Student
WHERE Sname = '王非') AND Sno > (SELECT Sno
FROM Student
WHERE Sname = '王非')
9.求年龄大于女同学平均年龄的男学生姓名和年龄
SELECT Sname,Sage
FROM STUDENT
WHERE Sage > (SELECT AVG(SAGE)
FROM Student
WHERE Ssex = '女') AND Ssex = '男'
10.求年龄大于所有女同学年龄的男学生姓名和年龄
SELECT Sname,Sage
FROM Student
WHERE Sage >(SELECT MAX(SAGE)
FROM Student
WHERE Ssex = '女') AND Ssex = '男'
11.检索所有比“王华”年龄大的学生姓名、年龄和性别。
SELECT SNAME,SAGE,SSEX
FROM STUDENT
WHERE Sage > (SELECT SAGE
FROM Student
WHERE SNAME = '王华')
12.检索选修4门以上课程的学生总成绩(不统计不及格的课程),并要求按总成绩的降序排列出来
SELECT SNO,SUM(GRADE)
FROM SC
WHERE SNO IN(SELECT SNO
FROM SC
GROUP BY SNO
HAVING COUNT(*)>4) AND GRADE>=60
GROUP BY SNO
ORDER BY SUM(GRADE) DESC
13. 查询选修’8105’课程的成绩高于’980302’号同学成绩的所有同学的记录(学号和成绩)
SELECT SNO,GRADE
FROM SC
WHERE CNO = '8105' AND GRADE >(SELECT GRADE
FROM SC
WHERE SNO = '980302' AND CNO = '8105')