一道关联子查询的sql题

一道关联子查询的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
          );

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值