SQL 语句练习
10-4 查询选修人数超过2人且成绩都在60分以上的课程 (10分)
本题目要求编写SQL语句,查询选修人数超过2人且成绩都在60分以上的课程的课程名、最高成绩、最低成绩和平均成绩。
提示:请使用SELECT语句作答。
表结构:
请在这里写定义表结构的SQL语句。例如:
CREATE TABLE major
(mno
char(2) NOT NULL,mname
varchar(20) NOT NULL,
PRIMARY KEY (mno
)
);
CREATE TABLE stu
(sno
char(4) NOT NULL,sname
char(8) NOT NULL,sex
tinyint(1) DEFAULT NULL,mno
char(2) DEFAULT NULL,birdate
datetime DEFAULT NULL,memo
text,
PRIMARY KEY (sno
),
KEY fk_stu_mno
(mno
),
CONSTRAINT fk_stu_mno
FOREIGN KEY (mno
) REFERENCES major
(mno
)
);
CREATE TABLE cou
(cno
char(4) NOT NULL,cname
varchar(30) NOT NULL,credit
smallint(6) DEFAULT NULL,ptime
char(5) DEFAULT NULL,teacher
char(10) DEFAULT NULL,
PRIMARY KEY (cno
)
);
CREATE TABLE sc
(sno
char(4) NOT NULL,cno
char(4) NOT NULL,grade
decimal(6,1) DEFAULT NULL,
PRIMARY KEY (sno
,cno
),
KEY fk_sc_cno
(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表:
输出样例:
请在这里给出输出样例。例如:
思路, 简单除法运算,考虑空值即可
题解代码如下:
select sc.cno as 课程号,cname as 课程名,max(grade) as
最高成绩,min(grade) as 最低成绩, avg(grade) as
平均成绩 from sc,cou where sc.cno=cou.cno and not exists
(select cno from sc where sc.cno=cou.cno and (grade is null or grade<60))
GROUP BY sc.cno having count(sno)>=2
运行结果: