MyPersistence

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

一、简介

  今天在网上搜到几道数据库题还不错,是关于数据库表的操作的题目,这类题目经常出现在面试的笔试题目中。 做了一遍,特在这里记录下来做个总结。 

二、题目及答案

  数据库中共有四张表,下面将以截图的方式说明:

老师信息表:                                   学生信息表:

  

 

课程表:                                        分数表:

 

1、查询"1"课程比"2"课程成绩高的所有学生的学号;

select a.S# from (
select  * 
from sc where C#=1 ) a 
inner join  (select  * 
from sc where C#=2)  b on a.S#=b.S#
where a.score>b.Score

2、查询平均成绩大于60分的学号和平均成绩;

select  S#,avg(score) as score
from sc 
group by s#
having avg(score)>60 

3、查询所有同学的学号、姓名、选课数、总成绩;

select  a.S#,Sname,
case when b.Num is null then 0 else b.Num end Num ,
case when  b.SumScore is null then 0 else  b.SumScore end SumScore
from student a left join 
(select S#,count(*) Num,sum(score) SumScore from SC group by S# )b on a.S#=b.S#

4、查询姓"李"的老师个数;

select  count(*) Num
from Teacher  
where Tname like '李%'

5、查询没学过"叶平"老师课的同学的学号、姓名;

select S#,Sname 
from student 
where S# not in (
select  distinct S# 
from SC c 
where exists  (
select  C# 
from Course a left join teacher b on a.T#=b.T# 
where  b.Tname='叶平' and c.C#=a.C#) )

6、查询学过"1"并且也学过编号"2"课程的同学的学号、姓名;

select a.S#,b.Sname from (
select a.S# 
from (
select  * 
from sc 
where C# in (1,2)) a
group by a.S# 
having count(*)=2) a  
left join Student b on a.S#=b.S#

select a.S#,C.Sname from (
select  * 
from sc where C#=1 ) a 
inner join  (select  * 
from sc where C#=2)  b on a.S#=b.S#
left join student c on a.S#=c.S#

7、查询学过"叶平"老师所交的所有课程的同学的学号、姓名;

select a.S#,b.Sname from (
select S# from (
select sc.* from sc  where C# in (
select  C# from Course a inner join 
Teacher b on a.T#=b.T# where b.tname='叶平' )     
) a group by S# 
having  count(*)=(select count(*) from Course a inner join 
Teacher b on a.T#=b.T# where b.tname='叶平')
)  a left join Student b on a.S#=b.S#

8、查询所有课程成绩小于60的同学的学号、姓名;

select distinct a.S#,c.Sname 
from sc  a left join Student c on a.S#=c.S# 
where  not exists (
select  S# 
from sc b where Score>60 and a.S#=b.S#) 

9、查询没有学所有课的同学的学号、姓名;

select a.* 
from  student  a 
where a.S# not in (select  S# 
from sc 
group by S# 
having count(*)=(
select count(*)
from Course)) 

10、查询至少有一门课与"张三"的同学相同的同学的学号和姓名;

select  distinct a.S#,b.Sname  
from sc a left join Student b on a.S#=b.S#
where C#  in (
select a.C# 
from Sc a left join student b on a.S#=b.S#
where b.Sname='张三')                                       
and a.S#<> (select  S# from Student where Sname='张三')    

11、查询学过学号为"1"同学所有课的其他同学学号和姓名;

select a.S#,b.Sname  from (
select a.S# 
from (
select * 
from sc  a
where S#<>1 and exists (select  * 
from sc  b where S#=1 and a.C#=b.C#  ) )  a
group by   a.S#
having count(*)= (select  count(*) 
from sc  b where S#=1)  ) a left join Student b on a.S#=b.S# 

 

 

 

  

posted on 2016-04-11 15:18  MyPersistence  阅读(453)  评论(0编辑  收藏  举报