查询课程1的成绩 比 课程2的成绩 高 的所有学生的学号.
select a.sno from
(select sno,score from sc where cno=1) a,
(select sno,score from sc where cno=2) b
where a.score>b.score and a.sno=b.sno
From函数中是可以对函数起别名的
只能是唯一的一个学生,自己的一课程比二课程的分数高
题中a.sno=b.sno显然就是将选择一的和选择二的合在一起,这样就变成了一个学生的
--2、查询平均成绩大于60分的同学的学号和平均成绩;
select sno,avg(score) as sscore from sc group by sno having avg(score) >60
--select a.sno as "学号", avg(a.score) as "平均成绩"
--from
--(select sno,score from sc) a
--group by sno having avg(a.score)>60
但是写成这样就会出错:语法没错
--select a.sno as "学号", avg(a.score) as "平均成绩"
--from
--(select sno,score from sc) a
--where avg(a.score)>60
1每一个学生都是一个单元,是一个单元带动一个组的
所以在选择平均成绩大于60分的一定要选择
Group by 的使用
2想要给一个数进行改别名的时候,一定要先进行抽离,意思就是一个嵌套
(select sno ,grade from sc)
从一个函数里面那出来东西
--3、查询所有同学的学号、姓名、选课数、总成绩
select a.sno as 学号, b.sname as 姓名,
count(a.cno) as 选课数, sum(a.score) as 总成绩
from sc a, student b
where a.sno = b.sno
group by a.sno, b.sname
为什么在group by的后面加上了两个???
count函数的使用是可以在select上的
--3、查询所有同学的学号、姓名、选课数、总成绩
select student.sno as 学号, student.sname as 姓名,
count(sc.cno) as 选课数, sum(score) as 总成绩
from student left Outer join sc on student.sno = sc.sno
group by student.sno, sname
为什么在group by 的后面加上了两个变量,
Left outer join sc on 的使用是
将会把空值塞入到右表中
--4、查询姓“李”的老师的个数;
select count(distinct(tname)) from teacher where tname like '李%‘
这一个是高度的简介化所得到的东西
select tname as "姓名", count(distinct(tname)) as "人数"
from teacher
where tname like'李%'
group by tname
要那个分组依据元素,会以已经分完组后的形式显现出来
--5、查询没学过“叶平”老师课的同学的学号、姓名;
select student.sno,student.sname from student
where sno not in
(select distinct(sc.sno) from sc,course,teacher
where sc.cno=course.cno and teacher.tno=course.tno and teacher.tname='叶平')
这里以sc进行了一个多表连接,
进行了一个检验,先找到了曾经选修过李平老师的学生的学号,然后看看在不在里面。
以后的这种绝对化,像多对一,没办法进行的时候,可以反过来想一下
--6、查询同时学过课程1和课程2的同学的学号、姓名
select sno, sname from student
where sno in (select sno from sc where sc.cno = 1)
and sno in (select sno from sc where sc.cno = 2)
go
select c.sno, c.sname from
(select sno from sc where sc.cno = 1) a,
(select sno from sc where sc.cno = 2) b,
student c
where a.sno = b.sno and a.sno = c.sno
go
select student.sno,student.sname from student,sc where student.sno=sc.sno and sc.cno=1
and exists( Select * from sc as sc_2 where sc_2.sno=sc.sno and sc_2.cno=2)
go
利用自身连接的方法,可以得到两个的情况,而不需要采用减去的方法
我的qq是839356161
我是数据库的初级修炼者,欢迎大家和我交流