一道关联子查询的SQL题目
已知表结构如下:A表
year sid cid score
2001 001 1 60
2002 001 1 70
2001 001 2 80
2002 001 2 90
2001 002 1 70
2001 002 2 80
2001 001 3 80
2001 002 3 70
2002 001 3 80
统计2001年各门课程成绩超过平均成绩的记录
建立表结构如下:
-->删除表
drop table A ;
-->创建表
create table A (
year varchar(4),
sid varchar(5),
cid varchar(2),
score int(6),
primary key(year,sid,cid)
);
-->插入数据
insert into A values('2001','001','1',60);
insert into A values('2002','001','1',70);
insert into A values('2001','001','2',80);
insert into A values('2002','001','2',90);
insert into A values('2001','002','1',70);
insert into A values('2001','002','2',80);
insert into A values('2001','001','3',80);
insert into A values('2001','002','3',70);
insert into A values('2002','001','3',80);
commit;
查询语句如下:
查询过程如下:
1.首先要过滤出2001年的所有记录,且成绩大于某个值
select * from A where year='2001'and score > ?
2. 查找出每门课程在2001年的平均成绩
select avg(score) from A where year = '2001' group by cid
3.合并sql语句
合并过程中,第一个表中的cid和第二表中的cid相等(成绩高于平均成绩)
并且 第一个表中过年份和第二个表中的年份相等,这样才能保证上面两个子查询得到结果都是2001的。
select a.year,a.sid,a.cid,a.score from A a
where a.year = '2001' and a.score >=
(
select avg(b.score) from A b
where a.year = b.year and a.cid =b.cid
group by b.cid
);

2272

被折叠的 条评论
为什么被折叠?



