SQL语句建表、查询

1、建表
create Table Student(
Sno char(9) not null,
Sname char(20) not null,
Ssex char(2) null,
Sage smallint null,
Sdept char(20) null,
primary key (Sno)
);
create Table Course(
Cno char(4) not null,
Cname char(40) not null,
Cpno char(4) null,
Ccredit smallint null,
primary key (Cno),
foreign key(Cpno) references Course(Cno)
);
create Table SC(
Sno char(9) not null,
Cno char(4),
primary key(Sno,Cno),
foreign key(Sno) references Student(Sno),
foreign key(Cno) references Course(Cno)
);
select * from SC
2、查询
(1)向SC表中增加成绩(Grade)列,其数据类型为短整型。
alter Table SC add Grade Smallint;
(2)查询所有课程的课程号和课程名。
select Cno,Cname from Course;
(3)查询全体学生的记录。
select * from Student;
(4)查询学生表中的所有的系。
select Sdept from Student;
(5)查询全体学生的姓名、出生年份和所在的院系,并为出生年份和所在院系两列分 别起别名为sbirth,department,并将系名全部转换成小写字母
select Sname,2009-Sage sbirth,LOWER(Sdept) department from Student;
(6)求数学系学生的学号和姓名。
select Sname,Sno from Student where Sdept=‘MA’;
(7)查询所有考试成绩在80分以下的学生学号、课程号。
select Sno,Cno from SC where Grade<‘80’;
(8)查询学分在2~7之间的课程信息。
select from Course where Ccredit between 2 and 7;
(9)查询课程名为DB_Design课程的课程号和学分。
select Cno,Ccredit from Course where Cname like ‘DB_Design’;
(10) 查询没有先修课的课程号、课程名及学分。
select Cno,Cname,Ccredit from Course where Cpno is null;
(11)查询信息系学生性别为男且年龄小于20岁的学生姓名。
select Sname from Student where Sdept=‘IS’ and Ssex='男’and Sage<20;
(12)查询选修了3号课程的学生的学号及成绩,并要求对查询结果按成绩的降序排列,如果成绩相同按学号的升序排列。
select Sno,Grade from SC where Cno=‘3’ ORDER by Grade DESC ;
(13)查询课程的总数。
select COUNT(
) from Course;
(14)查询选修2号课程的学生平均成绩和最高成绩,并分别为平均成绩和最高成绩起别名为AVG,MAX。
select AVG(Grade) AVG,max(Grade)MAX from SC where Cno=‘2’;
(15)查询每个学生的选课门数,要求输出学生学号及选课的门数。
select Sno,COUNT(Cno)from SC group by Sno;
(16)查询选修了2门及以上的课程的学生学号。
select Sno from SC Group by Sno having COUNT(*)>=2;

猜你喜欢

转载自blog.csdn.net/qq_43254543/article/details/89001084