--1使用子查询实现命题查询出所有没有参加考试的同学的学生编号,姓名。
use TextSchool
select Fstubianhao,FstuName from T_Student
where T_Student.FstuId not in (select T_Score.FstuId from T_Score)
--2使用联接重做:查询出所有没有参加考试的同学的学生编号,姓名。
--左外链接
select * from
(select Fstubianhao,FstuName,FstuAge,T_Score.* from T_Student
left outer join T_Score
on T_Score.FstuId=T_Student.FstuId)as Tbl
where FstuId is null
--右外连接
select * from
(select Fstubianhao,FstuName,FstuAge,T_Score.* from T_Score
right outer join T_Student
on T_Score.FstuId=T_Student.FstuId)as Tbl
where FstuId is null
--3查询所有英语及格的学生姓名、年龄及成绩
select FstuName,FstuAge,FEnglish from T_Student
inner join T_Score on T_Score.FstuId=T_Student.FstuId
where T_Score.FEnglish>=60
--4查询所有参加考试的(english分数不为null)学生姓名、年龄及成绩
select * from T_Student
select * from T_Score
select FstuName,FstuAge,FEnglish,Fmath from T_Student
inner join T_Score on T_Student.FstuId=T_Score.FstuId
where T_Score.FEnglish is not null
--5查询所有学生(报考的和未报考的)的学生姓名、年龄、成绩,如果报考了,但是没有参加考试显示缺考,如果小于english&math小于60分显示不及格,如果没有报考显示没有报考(添加两列 ,“是否报考”,“是否合格”)
select * from T_Student
select * from T_Score
select FstuName,FstuAge,
case
when FEnglish is null then '缺考'
else CONVERT(varchar(50), FEnglish)
end as FEnglish,
Fmath=
case
when Fmath is null then '缺考'
else CONVERT(varchar(50), Fmath)
end ,
是否报考=
case
when FscoreId is null then '未报考'
else '已报考'
end,
是否合格=case
when FEnglish>=60 and Fmath>=60 then '合格'
else '不合格'
end
from T_Student
left join T_Score on T_Score.FstuId=T_Student.FstuId
--6新建 临时表(#MyStudents,包含2个字段分别为sName、sAge),并将Mystudents中的相应数据copy其中。
use Text
create table #Mystudents
(
sName nvarchar(50),
sAge int
)
insert into #Mystudents
select FName,FAge from Mystudents
select * from #Mystudents
delete from #Mystudents
where FName in('康凯','李昂','李辰')
--7定义表变量、插入数据并查询:
declare @varTbl table (coll int ,coll2 varchar(30))
insert into @varTbl values(100,'A')
insert into @varTbl values(101,'B')
select * from @varTbl
--8新建视图,修改视图,删除视图
use TextSchool
create view vw_StudentScore
as
select FstuName,FstuAge,
case
when FEnglish is null then '缺考'
else CONVERT(varchar(50), FEnglish)
end as FEnglish,
Fmath=
case
when Fmath is null then '缺考'
else CONVERT(varchar(50), Fmath)
end ,
是否报考=
case
when FscoreId is null then '未报考'
else '已报考'
end,
是否合格=case
when FEnglish>=60 and Fmath>=60 then '合格'
else '不合格'
end
from T_Student
left join T_Score on T_Score.FstuId=T_Student.FstuId
select * from vw_StudentScore
alter view vw_StudentScore
as
select * from T_Student
update T_Student set FstuName='山西关羽' where FstuName='关羽'
--我们可以把很长很长的查询语句,放到一个视图中,这样我们在要得到长长的查询语句的结果时候,就可以,不执行这段语句,而是查询一下相应的视图即可
--视图类死于一个表,这个表和临时表不同,他不会在回话结束时适放掉,每次都能用
--视图中不存放数据,只存放查询