數據庫 單表查詢

建立三個表:Student(學生信息表),Course(課程表),SC(學生選課表)

create table Student(Sno char(9)PRIMARY KEY,
Sname char(20)UNIQUE,
Ssex char(2),
Sage SMALLINT,
Sdept char(20));

create table Course(Cno char(4)PRIMARY KEY,
Cname char(40) not null,
Cpno char(4),
Ccredit SMALLINT,
FOREIGN KEY (Cpno)REFERENCES Course(Cno));

create table SC(Sno char(9),
Cno char(4),
Grade SMALLINT,
PRIMARY KEY(Sno,Cno),
FOREIGN KEY (Sno)REFERENCES Student(Sno),
FOREIGN KEY (Cno)REFERENCES Course(Cno),);

存入信息:

insert into Student () values ();
insert into Course () values ();
insert into SC () values ();

向student表添加記錄10條記錄添加方式一樣

insert into Student (Sno,Sname,Ssex,Sage,Sdept) values

('201616041','張三','男',20,'CS');

 

向course表添加記錄10條記錄添加方式一樣

insert into Course (Cno,Cname,Cpno,Ccredit) Values

('1102','數學',NULL,2);

 

向sc表添加記錄10條記錄添加方式一樣

insert into SC(Sno,Cno,Grade) values

('201616040','1101',54);

 

Student的執行增刪改操作三條語句分別爲插入,修改,刪除

insert into Student (Sno,Sname,Ssex,Sage,Sdept) values

('201616055','宋十五','男',22,'CS');

update Student set Sage = 50 where Sno='201616055';

delete from Student where Sno='201616055';

 

Course的執行增刪改操作三條語句分別爲修改,插入,刪除

update Course set Ccredit = 10 where Cno='1101';

insert into Course(Cno,Cname,Cpno,Ccredit) values

('1111','政治',null,4);

delete from Course where Cno='1109';

delete from Course where Cno='1103';

 

SC的執行增刪改操作三條語句分別爲插入,修改,刪除

insert into SC(Sno,Cno,Grade) values

('201616058','1101',22);

update SC set Cno=1106 where Sno='201616058';

delete from SC where Sno='201616040';

 

Student表做修改表結構練習依次是增加列,修改列的屬性,修改列的名稱,刪除列

alter table Student add CardID varchar(16);

alter table Student alter column CardID varchar(400) ;

EXEC sp_rename 'Student.CardID','CardIDTest';

alter table Student drop column CardIDTest;

select * from Student where Sdept='CS'; //查詢計算機系學生的信息;

select count(*) from Student;           //查詢全體學生的人數;

select Ssex, count(Ssex) 人數 from Student group by Ssex;  //查詢全體男生人數和女生人數;

//查詢每個系中的男生人數並按人數的降序排列;
select Sdept,Ssex,count(Sdept) 人數 
    from Student 
    group by Ssex ,Sdept 
    having Ssex='男' 
    order by count(Sdept);

select * from Student Where Sname LIKE '%十%';  //查詢名字中帶“十”的學生信息;

//求被選修的各門課程的平均成績和選修該課程的人數;
select Cno 課程號,count(Sno) 人數,AVG(Grade) 平均成績 
    from SC 
    where Grade is not null 
    group by Cno;

//查找選修課程超過2門且成績都在80分以上的學生的學號。由於最初使的表不存在這樣的學生,於是我在SC表中又添加了一行201616044學生的信息 insert into SC values ('201616044','1108',98);
select Sno 
    from sc 
    where Grade>80 
    group by sno 
    having count(Sno)>=2;

 單表查詢(針對上述三個表):

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章