【SQL27】查询既学过'001'课程也学过'003'号课程的学生ID

有一张成绩表SC,表结构为SC(sid,cid,course),分部对应是学生ID,课程ID和学生成绩,有如下测试数据

sid         cid             course
1           001             67
1           002             89
1           003             94
2           001             95
2           002             88
2           004             78
3           001             94
3           002             77
3           003             90

查询既学过'001'课程,也学过'003'号课程的学生ID 预期结果为
1
3

解决:

select a.sid
  from (
        select sid
              ,cid
          from sc a
         where cid = '001'
        ) a
  inner join (
              select sid
                    ,cid
                from sc a
               where cid = '003'
              ) b
     on a.sid = b.sid
;
sid
1
3


备注:建表和数据
create table sc(s_id int,c_id varchar(10),course int);
insert into sc values(1,'001',67);
insert into sc values(1,'002',89);
insert into sc values(1,'003',94);
insert into sc values(2,'001',95);
insert into sc values(2,'002',88);
insert into sc values(2,'004',78);
insert into sc values(3,'001',94);
insert into sc values(3,'002',77);
insert into sc values(3,'003',90);

 

 

你可能感兴趣的:(每日一练)