【Sql】经典sql语句

时间:2023-01-19 20:07:11

参考网页:https://www.cnblogs.com/qixuejia/p/3637735.html

1./**查询课程1比课程2,成绩高的学生学号
1.分析这些元素都在一个表里,但是上下两条记录,是无法比较的,所以需要将他们自连接,到一个表
2.课程1为一张表,课程2为一张表,将他们按学号相同拼起来,就可以进行比较了。
**/
select a.s# from
(select s#,score from sc where c# =1)a ,
(select s#,score from sc where c#=2)b
where a.s#=b.s# and a.score>b.score;

/**用left join会将所有记录查询出来,如果右表的记录不存在,则置为null
**/
select a.s#, a.score,b.score from
(select s#,score from sc where c# =1)a left join
(select s#,score from sc where c#=2)b
on a.s#=b.s# and a.score>b.score
where b.score is not null;

2./**查询平均成绩大于60分的学生学号,平均成绩
1.这在一个表里即可以查询到
2.按学号分组,查询平均成绩即可
**/
select s#,AVG(score)as avg
from sc
group by s#
having AVG(score)>60;

3./**查询全校学生的学号,姓名,选课数,总成绩
1.group by 里的内容,必须出现在select后,而聚合函数里的内容,不需要出现在group by后
2.聚合函数的列名为空,可以用as赋予一个别名
**/
select sc.s#,student.sname,COUNT(sc.c#) as 课程数,SUM(score) as 总成绩
from sc,student
where sc.s#=student.s#
group by sc.s#,sname;

4./**查询姓周的老师的个数
**/
select COUNT(*) from teacher
where tname like '周%';

5./**查询没有学过叶平老师的课的同学的学号,姓名
1.分析字段涉及到4个表
2.主要的逻辑在sc表,将course表,teacher表用他们相同的字段,拼起来
3.当teacher=叶平老师时,即代表改行的学生是学过叶平老师的课的
4.再将学号进行去重,得到学过叶平老师课的学号
5.学生表里的学号,不在上面的记录里,则表示没有学过叶平老师的课
**/
select s#,sname from student
where s# not in
(select distinct sc.s# from sc,teacher,course
where sc.c# = course.c# and course.t#=teacher.t# and tname = '叶平')

6./**查询学过课程1,也学过课程2的学生学号,姓名
1.查询出学过课程1的所有学号
2.查询出学过课程2的所有学号
3.如果学号同时在这两个结果集了,则说明既学过1,也学过2
**/
select s#,sname
from student
where s# in
(select s# from sc where c#=1)and
s# in
(select s# from sc where c#=2);select Student.S#,Student.Sname

from Student,SC
where Student.S#=SC.S# and SC.C#='001'
and exists( Select * from SC as SC_2 where SC_2.S#=SC.S# and SC_2.C#='002');

7./**查询出所有学过叶平老师的课程的同学的学号,姓名
1.查询出叶平老师教过的课程数
2.查询出学过叶平老师的课的同学学号
3.按学号分组,得到数量
4.如果两者的值一样,则说明该同学学过叶平老师所教的所有课程
**/
select s#,sname from student
where s# in(
select sc.S# from SC ,Course ,Teacher
where SC.C#=Course.C# and Teacher.T#=Course.T# and Teacher.Tname='叶平'
group by sc.s#
having COUNT(*)=
(select COUNT(*)from
course,teacher
where course.t#=teacher.t# and teacher.tname='叶平')
);

8./**查询出所有成绩小于60分的同学的学号,姓名
**/
select s#,sname from student
where s# not in
(select s# from school.dbo.sc where score>=80);

9./**查询没有学全所有课程的
**/
select s# from sc
group by s#
having count(*)<
(select count(*)from course);

10./**查询至少有一门课程与学号1的同学所学的相同的学号和姓名
**/
select distinct student.s# ,sname
from student,sc where
student.s# = sc.s# and
c# in(
select c# from sc
where s#=1
)