搜索
简帛阁>技术文章>SQL Server练习经典题及其详解

SQL Server练习经典题及其详解

近期由于工作需求,需要使用到sql server的相关内容,由于此前主要使用mysql及mongodb数据,所以希望通过练习来掌握sql server中与mysql语句中的差异性。以下将列出此次练习使用的相关材料(包括数据库的创建语句,题目,答案详解及部分个人注释)以及在练习过程中发现的sql server使用过程中需要注意的点(区别于mysql查询语句)。

本博客题目案例来源网络,经过筛选进行汇总如下(40题),查询语句全部真实编写并测试有效。

在练习之前,先总结下整体练习过程中发现的sql server查询语句和mysql查询语句构建过程中的区别:(欢迎评论区补充和建议)

①sql server中的group by语句必须包含select中除聚合函数sum(),count()等的所有查询结果集(由于group by是进行分组操作,因此建议在书写查询语句时注意查询结果集的先后顺序)

②sql server中的变量声明与mysql有很大差别,练习中我使用declare声明变量类型,用set定义变量数据,形成系统可读的自定义变量数据。(具体案例参考问题37,38)

 

相关数据表介绍:

--1.学生表
Student(SId,Sname,Sage,Ssex)
--SId 学生编号,Sname 学生姓名,Sage 出生年月,Ssex 学生性别

--2.课程表
Course(CId,Cname,TId)
--CId 课程编号,Cname 课程名称,TId 教师编号

--3.教师表
Teacher(TId,Tname)
--TId 教师编号,Tname 教师姓名

--4.成绩表
SC(SId,CId,score)
--SId 学生编号,CId 课程编号,score 分数

创建相关数据表,sql语句如下:

学生表 Student

create table Student(SId varchar(10),Sname varchar(10),Sage datetime,Ssex varchar(10));
insert into Student values('01' , '赵雷' , '1990-01-01' , '男');
insert into Student values('02' , '钱电' , '1990-12-21' , '男');
insert into Student values('03' , '孙风' , '1990-12-20' , '男');
insert into Student values('04' , '李云' , '1990-12-06' , '男');
insert into Student values('05' , '周梅' , '1991-12-01' , '女');
insert into Student values('06' , '吴兰' , '1992-01-01' , '女');
insert into Student values('07' , '郑竹' , '1989-01-01' , '女');
insert into Student values('09' , '张三' , '2017-12-20' , '女');
insert into Student values('10' , '李四' , '2017-12-25' , '女');
insert into Student values('11' , '李四' , '2012-06-06' , '女');
insert into Student values('12' , '赵六' , '2013-06-13' , '女');
insert into Student values('13' , '孙七' , '2014-06-01' , '女');

科目表 Course

create table Course(CId varchar(10),Cname nvarchar(10),TId varchar(10));
insert into Course values('01' , '语文' , '02');
insert into Course values('02' , '数学' , '01');
insert into Course values('03' , '英语' , '03');

教师表 Teacher

create table Teacher(TId varchar(10),Tname varchar(10));
insert into Teacher values('01' , '张三');
insert into Teacher values('02' , '李四');
insert into Teacher values('03' , '王五');

成绩表 Sc

create table SC(SId varchar(10),CId varchar(10),score decimal(18,1));
insert into SC values('01' , '01' , 80);
insert into SC values('01' , '02' , 90);
insert into SC values('01' , '03' , 99);
insert into SC values('02' , '01' , 70);
insert into SC values('02' , '02' , 60);
insert into SC values('02' , '03' , 80);
insert into SC values('03' , '01' , 80);
insert into SC values('03' , '02' , 80);
insert into SC values('03' , '03' , 80);
insert into SC values('04' , '01' , 50);
insert into SC values('04' , '02' , 30);
insert into SC values('04' , '03' , 20);
insert into SC values('05' , '01' , 76);
insert into SC values('05' , '02' , 87);
insert into SC values('06' , '01' , 31);
insert into SC values('06' , '03' , 34);
insert into SC values('07' , '02' , 89);
insert into SC values('07' , '03' , 98);

练习题目

(我采用列表链接,有需要指定的相关题目解答,请直接点击链接跳转)

1.查询" 01 "课程比" 02 "课程成绩高的学生的信息及课程分数

2.查询同时存在" 01 "课程和" 02 "课程的学生数据

3.查询存在" 01 "课程但可能不存在" 02 "课程的情况(不存在时显示为 null )

4.查询不存在" 01 "课程但存在" 02 "课程的情况

5.查询平均成绩大于等于 60 分的同学的学生编号和学生姓名和平均成绩

6.查询所有同学的学生编号、学生姓名、选课总数、所有课程的成绩总和

7.查询学过「张三」老师授课的同学的信息

8. 查询没有学全所有课程的同学的信息

9.查询至少有一门课与学号为" 01 "的同学所学相同的同学的信息

10.查询和" 01 "号的同学学习的课程完全相同的其他同学的信息

11. 查询没学过"张三"老师讲授的任一门课程的学生姓名

12.查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩

13.检索" 01 "课程分数小于 60,按分数降序排列的学生信息

14. 按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩

15.查询各科成绩最高分、最低分和平均分,选修人数,及格率,中等率,优良率,优秀率:

16.按各科成绩进行排序,并显示排名, Score 重复时保留名次空缺

17.查询学生的总成绩,并进行排名,总分重复时不保留名次空缺 

18.统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[60-0] 及所占百分比

19.查询各科成绩前三名的记录

20.查询出只选修两门课程的学生学号和姓名

21. 查询同名学生名单,并统计同名人数

22. 查询 1990 年出生的学生名单

23.查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列

24.查询平均成绩大于等于 85 的所有学生的学号、姓名和平均成绩

25.查询课程名称为「数学」,且分数低于 60 的学生姓名和分数

26.查询所有学生的课程及分数情况(存在学生没成绩,没选课的情况)

27.查询任何一门课程成绩在 70 分以上的姓名、课程名称和分数

28. 查询存在不及格的课程

29.查询课程编号为 01 且课程成绩在 80 分及以上的学生的学号和姓名

30.成绩有重复的情况下,查询选修「张三」老师所授课程的学生中,成绩最高的学生信息及其成绩

31.查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩

32.查询每门功成绩最好的前两名

33. 统计每门课程的学生选修人数(超过 5 人的课程才统计

34.检索至少选修两门课程的学生学号

35.查询选修了全部课程的学生信息

36. 按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一

37.查询本周过生日的学生

38.查询下周过生日的学生

39.查询本月过生日的学生 

40. 查询下月过生日的学生

解答

  1. 查询" 01 "课程比" 02 "课程成绩高的学生的信息及课程分数
--方法一:右连接
select * from student
right join(
select t1.sid,score1,score2
from (select sid,score as score1 from sc where sc.cid = '01') as t1,
	(select sid,score as score2 from sc where sc.cid = '02') as t2
where t1.sid = t2.sid and t1.score1 >t2.score2)as r
on student.sid = r.sid

 

--方法二:嵌套查询
select * from
(select t1.sid,score1,score2
from (select sid,score as score1 from sc where sc.cid = '01') as t1,
(select sid,score as score2 from sc where sc.cid = '02') as t2
where t1.sid = t2.sid and t1.score1 > t2.score2
)as r
left join student
on student.sid = r.sid

2.查询同时存在" 01 "课程和" 02 "课程的学生数据

select * 
from (select * from sc where sc.cid = '01')as t1,
(select * from sc where sc.cid = '02') as t2
where t1.sid = t2.sid

3.查询存在" 01 "课程但可能不存在" 02 "课程的情况(不存在时显示为 null )

此处的可能不存在表示2种情形,“01”课程一定存在,“02”课程可以存在也可以不存在

--左右连接都可
select *
from (select * from sc where sc.cid = '01')as t1
left join (select * from sc where sc.cid = '02')as t2
on t1.sid = t2.sid;



select *
from (select * from sc where sc.cid = '02')as t2
right join (select * from sc where sc.cid = '01')as t1
on t1.sid = t2.sid

4.查询不存在" 01 "课程但存在" 02 "课程的情况

select *
from sc
where sc.sid not in (select sid from sc where sc.cid = '01')
and sc.cid = '02'

5.查询平均成绩大于等于 60 分的同学的学生编号和学生姓名和平均成绩

--方法一:
select st.sid,st.sname,r.avg_score
from student as st,(select sid,avg(score) as avg_score from sc group by sid having avg(score) >60) as r
where st.sid = r.sid;

--方法二:
select st.sid,st.sname from student as st
right join(select sid,avg(score) as avg_score from sc group by sid having avg(score) >60) as t
on st.sid = t.sid;

--方法三:
select t.sid,r.sname,t.avg_score
from (select sid,avg(score) as avg_score  from sc group by sid having avg(score) >60) as t
left join (select st.sid,st.sname from student as st) as r
on t.sid = r.sid

6.查询所有同学的学生编号、学生姓名、选课总数、所有课程的成绩总和

--联合查询不会显示没选课的学生:
select st.sid,st.sname,t.cnums,t.scoresum
from student as st,(select sid,count(cid) as cnums,sum(score) as scoresum
					from sc
					group by sid)as t
where st.sid = t.sid;


--显示没选课的学生(显示为null),需要使用join
select st.sid,st.sname,t.cnums,t.scoresum
from Student as st
left join (select sid,count(sc.cid) as cnums,sum(sc.score) as scoresum
			from sc
			group by sid) as t
on st.sid = t.sid;

select s.sid,s.sname,t.cnums,t.scoresum
from ((select st.sid,st.sname from student as st) as s
		left join 
		(select sc.sid,count(sc.cid) as cnums,sum(sc.score) as scoresum
		from sc
		group by sc.sid)as t
on s.sid = t.sid)

7.查询学过「张三」老师授课的同学的信息

select st.*
from student as st,course,teacher,sc
where st.sid = sc.sid
and sc.cid = course.cid
and course.tid = teacher.tid
and teacher.tname = '张三'

8. 查询没有学全所有课程的同学的信息
--因为有学生什么课都没有选,反向思考,先查询选了所有课的学生,再选择这些人之外的学生.

select * 
from student
where student.sid not in 
(select sc.sid 
from sc
group by sc.sid
having count(sc.cid) = (select count(course.cid) from course))

9.查询至少有一门课与学号为" 01 "的同学所学相同的同学的信息

select *
from student
where student.sid in
(select sc.sid 
from sc
where sc.cid in (select cid from sc where sc.sid = '01'))

10.查询和" 01 "号的同学学习的课程完全相同的其他同学的信息

--思路 :  查询 和 01号同学 课程 数量一样的 其他 同学
--再把数量一样的 同学 inner join  01 号同学。  如果数量 还是一样则课程相同 
select * from student s
where s.sid in (
select s.sid from 
(select s.sid,sc.cid from (
select sid from sc where sid != '01'
group by sid 
having count(*)=(select count(*) from sc where sid='01')
) s ,sc where sc.sid = s.sid
) s 
right join (select cid from sc where sid='01') c 
on c.cid = s.cid
group by sid 
having count(*)=(select count(*) from sc where sid='01')
)

11. 查询没学过"张三"老师讲授的任一门课程的学生姓名

select *
from student as st
where st.sid not in (
	select sid	from sc where sc.cid in (
		select course.cid from course where course.tid  in (
			select tid from teacher where tname = '张三')));


select * from student
where student.sid not in (select sc.sid from course,sc,teacher
					where sc.cid = course.cid
					and course.tid = teacher.tid
					and tname = '张三');

12.查询两门及其以上不及格课程的同学的学号,姓名及其平均成绩

select st.sid,st.sname,avg(sc.score) as avg_score
from student as st,sc
where st.sid = sc.sid
and sc.score < 60
group by st.sid,st.sname
having count(*) >=2;


select student.sid, student.sname, AVG(sc.score) as avg_score from student,sc
where student.sid = sc.sid and sc.score<60
group by student.sid,student.sname
having count(*)>1;

13.检索" 01 "课程分数小于 60,按分数降序排列的学生信息

select student.*,sc.score from student,sc
where student.sid = sc.sid
and sc.cid = '01'
and sc.score<60
--group by sc.sid
order by sc.score desc;

14. 按平均成绩从高到低显示所有学生的所有课程的成绩以及平均成绩

select * from sc
left join (select sid,avg(sc.score) as avg_score from sc group by sc.sid)as t
on sc.sid =t.sid
order by t.avg_score desc;

15.查询各科成绩最高分、最低分和平均分,选修人数,及格率,中等率,优良率,优秀率:

select 
sc.CId ,
max(sc.score)as 最高分,
min(sc.score)as 最低分,
AVG(sc.score)as 平均分,
count(*)as 选修人数,
sum(case when sc.score>=60 then 1 else 0 end )/count(*)as 及格率,
sum(case when sc.score>=70 and sc.score<80 then 1 else 0 end )/count(*)as 中等率,
sum(case when sc.score>=80 and sc.score<90 then 1 else 0 end )/count(*)as 优良率,
sum(case when sc.score>=90 then 1 else 0 end )/count(*)as 优秀率 
from sc
GROUP BY sc.CId
ORDER BY count(*)DESC, sc.CId ASC

16.按各科成绩进行排序,并显示排名, Score 重复时保留名次空缺

select a.cid, a.sid, a.score, count(b.score)+1 as rank
from sc as a 
left join sc as b 
on a.score<b.score and a.cid = b.cid
group by a.cid, a.sid,a.score
order by a.cid, rank ASC;

17.查询学生的总成绩,并进行排名,总分重复时不保留名次空缺 

select *,dense_rank()over(order by 总成绩 desc)排名 
from( select sc.sid,SUM(score)总成绩 from SC group by sc.sid)A;

18.统计各科成绩各分数段人数:课程编号,课程名称,[100-85],[85-70],[70-60],[60-0] 及所占百分比

select sc.cid,course.cname,
sum(case when sc.score <= 100 and sc.score > 85 then 1 else 0 end) as '[100-85]',
sum(case when sc.score <=85 and sc.score >70 then 1 else 0 end) as '[70-60]',
sum(case when sc.score <= 70 and sc.score > 60 then 1 else 0 end) as '[70-60]',
sum(case when sc.score <= 60 then 1 else 0 end) as '[60-0]'
from sc
left join course
on sc.cid = course.cid
group by sc.cid,course.cname;

19.查询各科成绩前三名的记录

select a.sid,a.cid,a.score from sc as a
left join sc as b
on a.cid =b.cid and a.score <b.score
group by a.sid,a.cid,a.score
having count(b.cid) <3
order by a.cid;

20.查询出只选修两门课程的学生学号和姓名

--嵌套查询
select sid,sname
from student
where student.sid in (select sc.sid from sc group by sc.sid having count(sc.cid)=2);

--联合查询
select student.sid,student.sname
from student,sc
where student.sid = sc.sid
group by student.sid,student.sname
having count(sc.cid) =2;

21. 查询同名学生名单,并统计同名人数

select sname,count(sname) as 同名人数
from student
group by sname
having count(*) >1;

--嵌套查询列出同名的全部学生的信息
select st.*
from student as st
where st.sname in (select sname from student group by sname having count(*) > 1)

22. 查询 1990 年出生的学生名单

select *
from student
where year(student.sage) = '1990';

23.查询每门课程的平均成绩,结果按平均成绩降序排列,平均成绩相同时,按课程编号升序排列

select cid,avg(score) as avg_score
from sc
group by cid
order by avg_score desc,cid asc;


select sc.cid,course.cname,avg(score) as avg_score
from sc,course
where sc.cid = course.cid
group by sc.cid,course.cname
order by avg_score desc,sc.cid asc;

24.查询平均成绩大于等于 85 的所有学生的学号、姓名和平均成绩

select st.sid,st.sname,avg(sc.score) as avg_score
from student as st,sc
where st.sid = sc.sid
group by st.sid,st.sname
having avg(sc.score) >=85;

25.查询课程名称为「数学」,且分数低于 60 的学生姓名和分数

select student.sname,sc.cid,sc.score
from student,sc,course
where student.sid = sc.sid
and sc.cid = course.cid
and course.cname = '数学'
group by student.sname,sc.score,sc.cid
having sc.score < 60;

26.查询所有学生的课程及分数情况(存在学生没成绩,没选课的情况)

--联合查询下---没选课的不会被查询出来
select st.sname,cid,score
from student as st,sc
where st.sid = sc.sid;
--group by st.sname,cid,score;

--级联查询下===没选课的情况也会根据用户人数显示选课为空
select student.sname,cid,score
from student
left join sc
on student.sid = sc.sid 

27.查询任何一门课程成绩在 70 分以上的姓名、课程名称和分数

select student.sname,course.cname,sc.score
from student,course,sc
where sc.score >70
and student.sid = sc.sid
and sc.cid = course.cid

28. 查询存在不及格的课程

select cid
from sc
where score < 60
group by cid;

select distinct sc.cid
from sc
where sc.score <60;

29.查询课程编号为 01 且课程成绩在 80 分及以上的学生的学号和姓名

select st.sid,st.sname,sc.score
from student as st,sc
where st.sid =sc.sid
and sc.cid = '01'
and sc.score >=80;

select *
from sc
where sc.cid = '01';

30.成绩有重复的情况下,查询选修「张三」老师所授课程的学生中,成绩最高的学生信息及其成绩

(此处在原始题目里还有一种不存在重复的情况下,但在我的理解中在查询有重复前提下已经包含了不重复的那种可能性,因此此处不再赘写)

--更新数据是为了能够看出重复数据的对比情况
UPDATE sc SET score=90
where sid = '07'
and cid ='02';

select student.*,sc.score
from student,sc,course,teacher
where student.sid =sc.sid
and sc.cid = course.cid
and course.tid = teacher.tid
and teacher.tname = '张三'
--having max(sc.score);
and sc.score = (
    select Max(sc.score) 
    from sc,student, teacher, course
    where teacher.tid = course.tid
    and sc.sid = student.sid
    and sc.cid = course.cid
    and teacher.tname = '张三'
);

31.查询不同课程成绩相同的学生的学生编号、课程编号、学生成绩

select a.sid,a.cid,a.score
from sc as a 
inner join sc as b
on a.sid = b.sid 
and a.cid != b.cid
and a.score = b.score
group by a.sid,a.cid,a.score;

32.查询每门功成绩最好的前两名

select a.sid,a.cid,a.score
from sc as a
left join sc as b
--此处使用cid进行级联,因为判定的分组依据是每门成绩
on a.cid = b.cid and a.score < b.score
group by a.sid,a.cid,a.score
having count(b.cid) <2
order by a.cid;

33. 统计每门课程的学生选修人数(超过 5 人的课程才统计)

select cid,count(sid) as ccnums
from sc
group by cid
having count(sid) >5

34.检索至少选修两门课程的学生学号

select sid,count(cid) as ccnums
from sc
group by sid
having count(cid) >=2

35.查询选修了全部课程的学生信息

select student.*
from student,sc
where student.sid = sc.sid
group by student.sid,student.sname,student.sage,student.ssex
having count(sc.cid) = (select distinct count(*) from course);

select *
from sc

36. 按照出生日期来算,当前月日 < 出生年月的月日则,年龄减一

select student.sid,student.sname,datediff(year,student.sage,getdate()) as 学生年龄
from student;

37.查询本周过生日的学生

备注:37,38题在测试过程中建议添加当前(你练习时间)周的周一,周日,上一周的周日,下一周的周一,周日,下下周的周一 这些sage时间数据的学生,便于理解查询代码中的参数含义

-- 本周一
declare @dt1 datetime
set @dt1 = DATEADD(week, DATEDIFF(week, 0, GETDATE()), 0)
-- 下周一
declare @dt2 datetime
set @dt2 = DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) + 1, -1)
--此处的-1是为了调整一周的时间段,若为0,则会包含下周一,为-1时,则仅包含当周周末
print @dt1
select * from student
WHERE DATEADD(Year,DATEDIFF(Year,student.sage,@dt1),student.sage)
BETWEEN @dt1 AND @dt2
OR DATEADD(Year,DATEDIFF(Year,student.sage,@dt2),student.sage)
BETWEEN @dt1 AND @dt2

38.查询下周过生日的学生

-- 下周一
declare @dt1 datetime
set @dt1 = DATEADD(week, DATEDIFF(week, 0, GETDATE())+1, 0)
-- 下下周一
declare @dt2 datetime
set @dt2 = DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) + 2, -1)
print @dt2
select * from student
WHERE DATEADD(Year,DATEDIFF(Year,student.sage,@dt1),student.sage)
BETWEEN @dt1 AND @dt2
OR DATEADD(Year,DATEDIFF(Year,student.sage,@dt2),student.sage)
BETWEEN @dt1 AND @dt2;

 

39.查询本月过生日的学生 

select *
from student
where month(student.sage) = month(getdate())

40. 查询下月过生日的学生

select *
from student
where month(student.sage) = month(getdate())+1

 以上为练习的全部内容,有错误欢迎评论指正,有不理解也可以留言咨询,看到消息回及时回复,谢谢!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


近期由于工作需求,需要使用到sqlserver的相关内容,由于此前主要使用mysql及mongodb数据,所以希望通过练习来掌握sqlserver中与mysql语句中的差异性。以下将列出此次练习使用的
前提需要工具:SQLQueryAnalyzer和SqlExecSunxVersion第一部分:有关去掉xp_cmdshell来保护系统的分析总结:首先知道一下语句:1去掉xp_cmdshell扩展过程
前言前面几篇文章我们讲解了索引有关知识,这一节我们再继续我们下面内容讲解,简短的内容,深入的理解。数据类型SQLServer支持两种字符数据类型,一种是常规,另外一种则是Unicode。常规数据类型包
FILESTREAM是SQLServer2008中的一个新特性,允许以独立文件的形式存放大对象数据,而不是以往一样将所有数据都保存到数据文件中。以往在对业务系统的文件进行管理时有两种方法,一种是将文件
MicrosoftSQLServer2000提供了两种主要机制来强制业务规则和数据完整性:约束和触发器。触发器是一种特殊类型的存储过程,它不同于之前的我们介绍的存储过程。触发器主要是通过事件进行触发被
1概述触发器是一种特殊的存储过程,它不能被显式地调用,而是在往表中插入记录﹑更新记录或者删除记录时被自动地激活。所以触发器可以用来实现对表实施复杂的完整性约束。2触发器的分类SQLServer2000
一、SQLProfiler工具简介SQLProfiler是一个图形界面和一组系统存储过程,其作用如下:1图形化监视SQLServer查询;2在后台收集查询信息;3分析性能;4诊断像死锁之类的问题;5调
在SQLServer2005数据库还原的过程中出现错误:备份集中的数据库备份与现有的'xxxx'数据库不同,网上找了几个解决方案测试,最终成功还原,特此记录下,提供给需要的人。第一步:如果你知道备份数
SQLServer在处理存储过程的时候,为了节省编译时间,是一次编译,多次重用。当第一次运行时代入值产生的执行计划,不适用后续代入的参数时,就产生了parametersniffing问题。create
之前学了几天的SQLServer,现在用C代码连接数据库了。需要使用C代码连接数据库,读取数据。涉及的类有:ConfigurationManageSqlConnectionSqlCommandSqlD