MOOC - 数据库系统概论 - 实验操作之多表查询

学生表:Student(Sno,Sname,Ssex,Sage,Sdept)
课程表:Course(Cno,Cname,Cpno,Ccredit)
学生选课表:SC(Sno,Cno,Grade)
注:性别为enum(‘男’or’女’),请使用KingBase语句进行答题,语句后要添加分号,否则语句视为错误

  1. 询学生姓名,对应的课程名和成绩(输出列为:SNAME,CNAME,GRADE)
SELECT sname SNAME,cname CNAME,grade GRADE 
from student,sc,course 
WHERE student.sno = sc.sno and course.cno = sc.cno;
  1. 查询每个学生的学号、姓名及其选修课程的名称和成绩(包括没有选修课程的学生情况(输出列为:SNO, SNAME, CNAME, GRADE)。
SELECT student.sno SNO,student.sname SNAME,course.CName CNAME,sc.Grade GRADE
from student,course,sc
WHERE student.sno = sc.sno and course.Cno = sc.cno;
  1. 查询其他系中比“信息学院”某一学生年龄小的学生姓名和年龄(输出列为:SNAME, SAGE)。
SELECT Sname , Sage 
FROM Student 
WHERE Sage< ANY (
SELECT Sage 
FROM Student 
WHERE Sdept='信息学院') AND Sdept <> '信息学院';
  1. 查询选修了全部课程的学生姓名(输出列为:SNAME)
SELECT Sname
         FROM Student
         WHERE NOT EXISTS
            (SELECT *
              FROM Course
              WHERE NOT EXISTS
                  (SELECT *
                   FROM SC
                   WHERE Sno= Student.Sno
                      AND Cno= Course.Cno));
  1. 查询选了经济控制论的学生中,成绩比名字为赵古韵的学生好的学生信息(输出列为STUDENT表全部列)
SELECT DISTINCT
	student.* 
FROM
	student,
	course,
	sc 
WHERE
	student.sno = sc.sno 
	AND course.Cno = sc.cno 
	AND course.CName = '经济控制论' 
	AND sc.Grade > (
	SELECT DISTINCT
		grade 
	FROM
		sc 
	WHERE
		grade = (
		SELECT
			sc.grade 
		FROM
			sc,
			course,
			student 
		WHERE
			sc.cno = course.cno 
			AND student.sno = sc.sno 
			AND course.CName = '经济控制论' 
			AND student.sname = '赵古韵' 
		));
  1. 统计每个学生所选课程的平均成绩(输出列为:SNAME,AVGSCORE)
SELECT Sname SNAME,avg(grade) AVGSCORE
FROM student s,sc
WHERE s.sno = sc.sno 
GROUP BY sname;
  1. 查询信息学院年龄在21岁以下的男生每个人所修课程的总学分,并按总学分进行升序排序(输出列为学号SNO、总学分CREDITSUM)
-- 个人感觉这样写没啥问题,但是不知道错在哪里,希望看透的松弟指点一哈
SELECT student.sno SNO,SUM(Ccredit) CREDITSUM
from sc,course,student
where sc.cno = course.cno and student.sno = sc.sno and student.Sdept='CS' and student.Ssex ='男' and student.Sage <21 
GROUP BY sc.sno
ORDER BY CREDITSUM asc;

--也想过了如果符合三个条件,但是没选课所以为0学分,或者null(啊西)
SELECT student.sno SNO,SUM(Ccredit) CREDITSUM
from sc,course,student
where sc.cno = course.cno and student.sno = sc.sno and student.Sdept='信息学院' and student.Ssex ='男' and student.Sage <21 
GROUP BY sc.sno
UNION
SELECT student.sno,0 CREDITSUM
from student LEFT JOIN sc on student.sno = sc.sno
where sc.cno is null and student.Sdept='信息学院' and student.Ssex ='男' and student.Sage <21
ORDER BY CREDITSUM asc;
  1. 查询各门课程的最高成绩的学生的姓名及其成绩(输出列为CNO,SNAME,GRADE)
SELECT SC.Cno,S.Sname, SC.grade
FROM SC, student S,
(select Cno, MAX(grade) grade FROM SC GROUP BY CNO) t1
WHERE SC.Sno = S.Sno
AND SC.Cno = t1.Cno
AND SC.grade = t1.grade;
  1. 查询选修了2012001001号学生所选修的全部课程的学生的姓名(输出列SNAME)
select SName SNAME
from student
where not exists ( SELECT * from (SELECT cno from sc WHERE sno = 2012001001) as S
WHERE not exists (SELECT * from sc WHERE cno = s.cno and sno = student.sno));

你可能感兴趣的:(MOOC,-,数据库系统概论,-,Keys)