数据库练习题4--sql简单查询(含答案)

实验目的
1.掌握SELECT语句的基本语法和查询条件表示方法;
2.掌握查询条件表达式和使用方法;
3.掌握GROUP BY 子句的作用和使用方法;
4.掌握HAVING子句的作用和使用方法;
5.掌握ORDER BY子句的作用和使用方法。

1.列出所有不姓刘的所有学生;

select *
from student
where sname not like '刘%'

2.列出姓“沈”且全名为3个汉字的学生;

select *
from student
where sname  like '沈%' and LEN(sname)=3

3.显示在1985年以后出生的学生的基本信息;

select * from student
where year(getdate())-sage>1985

4.查询出课程名含有“数据”字串的所有课程基本信息;

select * from course
where cname like '数据%'

5.显示学号第八位或者第九位是1、2、3、4或者9的学生的学号、姓名、性别、年龄及院系;

select * from student
where sno like '_______[12349]%' 
and sno like '________[12349]%'

6.列出选修了‘1’课程的学生,按成绩的降序排列;

select sno,grade from sc
where cno='1'
order by grade desc

7.列出同时选修“1”号课程和“2”号课程的所有学生的学号;

select sno from sc
where cno ='1' and 
sno in(select sno from sc where cno='2')

8.列出课程表中全部信息,按先修课的升序排列;

select * from course 
order by cpno asc

9.列出年龄超过平均值的所有学生名单,按年龄的降序显示;

select * from student
where sage>(select AVG(sage)from student)
order by sage desc

10.按照出生年份升序显示所有学生的学号、姓名、性别、出生年份及院系,在结果集中列标题分别指定为“学号,姓名,性别,出生年份,院系”;

select sno 学号,sname 姓名,ssex 性别,
YEAR(GETDATE ())-sage 出生年份,
sdept 院系 
from student
order by YEAR(GETDATE ())-sage asc

11.按照课程号、成绩降序显示课程成绩在70-80之间的学生的学号、课程号及成绩;

select * from sc
where grade>=70 and grade<80
order by cno desc,grade desc

12.显示学生信息表中的学生总人数及平均年龄,在结果集中列标题分别指定为“学生总人数,平均年龄”;

select COUNT(sno)学生总人数,
		AVG(sage)平均年龄
from student

13.显示选修的课程数大于3的各个学生的选修课程数;

select Sno,COUNT(sno)
from sc
group by sno having COUNT(sno)>3

14.按课程号降序显示选修各个课程的总人数、最高成绩、最低成绩及平均成绩;

select cno,COUNT(*),MAX(grade),
MIN(grade),AVG(grade)
from sc
group by cno
order by cno desc

15.显示平均成绩大于“200515001”学生平均成绩的各个学生的学号、平均成绩;

select sno,AVG(grade)
from sc
group by sno
having AVG(grade)>(select AVG(grade) 
from sc where sno='200515001')

16.显示选修各个课程的及格的人数、及格比率;

select COUNT(case when grade>=60 
then 1 end)各课程及格人数,
CAST(count(case when grade>=60 
then 1 end)/count(*)as float)及格比率
from sc
group by cno

17.显示选修课程数最多的学号及选修课程数最少的学号;

select sno 学号,COUNT(cno)选修课程数
from sc
group by sno
having COUNT(cno)>=all (select COUNT(cno)
from sc
group by sno)
or COUNT(cno)<=all(select COUNT(cno)
from sc
group by sno)

18.显示各个院系男女生人数,其中在结果集中列标题分别指定为“院系名称、男生人数、女生人数”;

select sdept as 院系名称,
COUNT(ssex) as 男生人数
from student
where ssex='男'
group by sdept

19.列出有二门以上课程(含两门)不及格的学生的学号及该学生的平均成绩;

select sno,AVG(grade)
from sc
where grade<60
group by sno
having COUNT (cno)>=2

猜你喜欢

转载自blog.csdn.net/ssdssa/article/details/108985057