题目要求
查询选修课程数在2门以上(含2门)且所有选课成绩都在80分以上(含80分)的学生的姓名、专业名及总学分。
提示:MSSQLServer 评测SQL语句。
表结构
-- 专业表
CREATE TABLE major (
mno char(2) NOT NULL,
mname nvarchar(20) NOT NULL,
PRIMARY KEY (mno)
);
-- 学生表
CREATE TABLE stu (
sno char(4) NOT NULL,
sname nvarchar(8) NOT NULL,
sex smallint DEFAULT NULL,
mno char(2) DEFAULT NULL,
birdate datetime DEFAULT NULL,
memo ntext,
PRIMARY KEY (sno),
CONSTRAINT fk_stu_mno FOREIGN KEY (mno) REFERENCES major (mno)
);
-- 课程表
CREATE TABLE cou (
cno char(4) NOT NULL,
cname nvarchar(30) NOT NULL,
credit smallint DEFAULT NULL,
ptime char(5) DEFAULT NULL,
teacher nvarchar(10) DEFAULT NULL,
PRIMARY KEY ( cno )
);
-- 学生选课成绩表
CREATE TABLE sc (
sno char(4) NOT NULL, -- 学生学号
cno char(4) NOT NULL, -- 课程号
grade decimal(4,1) DEFAULT NULL,
PRIMARY KEY ( sno , cno ),
CONSTRAINT fk_sc_cno FOREIGN KEY ( cno ) REFERENCES cou ( cno ),
CONSTRAINT fk_sc_sno FOREIGN KEY ( sno ) REFERENCES stu ( sno )
)
表样例
stu
表:
major
表:
cou
表:
sc
表:
输出样例:
编译代码:
1、使用join
select sname 姓名,mname 专业名,sum(credit) 总学分
from stu
join sc on stu.sno=sc.sno
join cou on sc.cno=cou.cno
join major on stu.mno=major.mno
where grade is not null
group by stu.sno,sname,mname
having count(sname)>=2 and min(grade)>=80
2、不使用join
select sname 姓名,mname 专业名,sum(credit) 总学分
from sc,stu,major,cou
where stu.sno=sc.sno and major.mno=stu.mno and cou.cno=sc.cno
group by sc.sno,sname,mname
having min(grade) >= 80 and count(sname) >= 2