1. 程式人生 > >SQL查詢有兩門以上不及格的學生及查詢出全部及格的學生

SQL查詢有兩門以上不及格的學生及查詢出全部及格的學生

font mar 結構 ont sel color 數據 nbsp code

1、表結構:

/*學生*/
create table student(
sno int not null primary key,
sname varchar(10)
);
/*課程*/
create table center(
cno int not null primary key,
cname varchar(10)
);
/*分數*/
create table sgrade(
sno int ,
cno int ,
sgrade int
);

2、插入數據:

insert into student values(11,a);
insert into student values(12,b
); insert into student values(13,c) insert into center values(21,aa); insert into center values(22,bb); insert into center values(23,cc) insert into sgrade values(11,21,54); insert into sgrade values(12,22,57); insert into sgrade values(11,21,51); insert into sgrade values(12,21,36); insert
into sgrade values(11,21,28); insert into sgrade values(12,22,42); insert into sgrade values(11,21,59) insert into sgrade values(11,21,79); insert into sgrade values(12,22,85); insert into sgrade values(11,21,90); insert into sgrade values(12,21,96); insert into sgrade values(11,21,98); insert into sgrade values
(12,22,94); insert into sgrade values(11,21,99)

3、查詢出有兩門以上不及格的學生:

SELECT s.sno,s.sname 
    from student s
    LEFT JOIN sgrade g on s.sno=g.sno
WHERE g.sgrade<60
GROUP BY s.sno HAVING COUNT(s.sno)>2

4、查詢出全部及格的學生:

SELECT * FROM student WHERE sno not in (
    SELECT s.sno
        from student s
        LEFT JOIN sgrade g on s.sno=g.sno
    WHERE g.sgrade<60 
)

SQL查詢有兩門以上不及格的學生及查詢出全部及格的學生