学生-课程数据库—初始sql语句(3)

group by子句:
如果select选择列表的列,既有普通列,又有聚集函数的列,则一定要分组(即加group by子句)。

如何分组?
答:把select选择列表的普通列,全部作为group by子句的分组列。

select *
from Student
order by Sdept,Sage desc

/*聚集函数*/
select COUNT(*) 学生总人数
from Student

select COUNT(distinct sno) 选修了课程的学生人数
from SC

select AVG(grade) 选修1号课程的学生的平均成绩
from SC
where Cno='1'

select MAX(grade) 选修1号课程的学生最高分数
from SC
where Cno='1'

select SUM(Ccredit) 学生201215121选修课程的总学分数
from Course,SC
where course.Cno=sc.Cno and Sno='201215121' and Grade>=60

select Cno 课程号,COUNT(*) 相应的选课人数
from SC
group by Cno

select Sno 选修了三门及以上课程的学生学号
from SC
group by Sno
having COUNT(*)>=3

/*求各个课程号,课程名及相应的选课人数*/
select SC.Cno,Cname,COUNT(*) 对应的选课人数
from Course,SC
where Course.Cno=SC.Cno
group by SC.Cno,Cname

select Sno,AVG(grade) 平均成绩
from SC
group by Sno
having AVG(grade)>=80

/*连接查询*/
select *
from Student,SC
where Student.Sno=SC.Sno

select Student.*,Cno,Grade
from Student,SC
where Student.Sno=SC.Sno

select SC.Sno,Sname
from Student,SC
where Student.Sno=SC.Sno and SC.Cno='2' and Grade>=90

select Student.*,Cno,Grade
from Student left outer join SC on (Student.Sno=SC.Sno)

select *
from SC right outer join Course on SC.Cno=Course.Cno

select *
from Course left outer join SC on SC.Cno=Course.Cno

select SC.Sno,Sname,Cname,Grade
from Student,SC,Course
where student.Sno=SC.Sno and SC.Cno=Course.Cno

/*查询每个学生的学号、姓名、选修的课程名及成绩,包括没有选修课程的学生,包括没有被选修的课程*/
select SC.Sno,Sname,Cname,Grade
from (Student full outer join SC on Student.Sno=SC.Sno)
      full outer join Course on SC.Cno=Course.Cno

附宝藏随笔:
传送门

猜你喜欢

转载自blog.csdn.net/qq_46139801/article/details/115328676