--IF ELSE
--特點:
--1.沒有{},使用begin...end
--2.有多重和嵌套
--3.if必須有處理語句,如果只有一句,也可以不使用begin..end,只包含后面一句
--4.沒有true/false的概念,只能使用關系運算符的條件表達式
--5.if后面的括號可以沒有
--計算office平均分數並輸出,如果平均分數超過60分輸出成績最高的三個學生的成績,否則輸出后三名的學生
go
declare @subjectname nvarchar(50)='office' --科目名稱
declare @subjectId int=(select subjectId
from subject where subjectname=@subjectname) --獲取科目ID
declare @avg int --科目平均分
set @avg=(select AVG(StudentResult) from Result
where SubjectId=@subjectId and StudentResult is not null) --獲取指定科目的平均分
--做判斷
if (@avg>=95)
begin
print '成績不錯。輸出前三名'
select top 3 * from Result where SubjectId=@subjectId
and StudentResult is not null order by StudentResult desc
end
else
begin
print '成績不好。輸出后三名'
select top 3 * from Result where SubjectId=@subjectId
and StudentResult is not null order by StudentResult
end
-------------
go
declare @name nvarchar(50)='office'--科目名稱
declare @id int =(select SubjectId from Subject where SubjectName =@name )--科目ID
declare @avg int = (select AVG (StudentResult ) from Result
where SubjectId =@id and StudentResult is not null )--獲取指定科目的平均分
--做判斷
if(@avg >=95)
begin
print '成績不錯,輸出前三名'
select top 3*from Result where SubjectId =@id and StudentResult is not null
order by StudentResult desc
end
else
begin
print '成績不好,輸出后三名'
select top 3 *from Result where SubjectId =@id and StudentResult is not null
order by StudentResult asc
end