數據庫的複雜查詢

實驗三 數據庫的複雜查詢

一、實驗學時

2學時

二、實驗目的

(1)熟練掌握複雜查詢的select語句。
(2)熟練掌握連接查詢方法。
(3)熟練掌握嵌套查詢方法。

三、實驗要求

(1)硬件設備:奔騰II或奔騰II以上計算機,局域網。
(2)軟件環境:WINDOWS 9X/NT、WINDOWS SERVER、WINDOWS XP、WINDOWS 7、SQL SERVER 2000/2005/2008中文版企業版或標準版。
(3)實驗課前預習,課後及時完成實驗內容。
(4)實驗過程及記錄按題目格式要求填寫代碼清單。

四、實驗內容

(一)複雜查詢
1.查詢比“王敏”年紀大的男學生信息。
T-SQL語句:
select Student.*
from Student
where Sage >(
select Sage
from Student
where Sname=‘王敏’
)and Ssex=‘男’
2.檢索所有學生的選課信息。(提示:使用外連接)
T-SQL語句:
select Student.Sno,Sname,Ssex,Sage,Sdept,Cno,Grade
from Student left outer join SC on(Student.Sno=SC.Sno)
3.查詢已選課學生的學號、姓名、課程名、成績。(提示:連接查詢)
T-SQL語句:
select Student.Sno,Sname,Cname,Grade
from Student,Course,SC
where Student.Sno=SC.Sno and Course.Cno=SC.Cno;
4.查詢選修了“信息系統”的學生的學號和姓名。
T-SQL語句:
select Student.Sno,Sname
from Student,Course,SC
where Course.Cname=‘信息系統’ and Course.Cno=SC.Cno AND Student.Sno=SC.Sno;
5.查詢與“劉晨”在同一個系的學生學號、姓名、性別。
子查詢T-SQL語句:
select Sdept
from Student
where Sname=‘劉晨’;

select Sno,Sname,Ssex
from Student
where Sdept=‘CS’
連接查詢T-SQL語句:
select Sno,Sname,Ssex
from Student
where Sdept in
(
select Sdept
from Student
where Sname=‘劉晨’
);
6.查詢其他系中比計算機科學系任一學生年齡大的學生的學號、姓名。
帶有ANY或ALL謂詞的子查詢語句:
select Sno,Sname
from Student
where Sage>any(
select Sage
from Student
where Sdept=‘CS’)
and Sdept<>‘CS’
用聚合函數實現:
select Sno,Sname
from Student
where Sage >(
select MIN(Sage)
from Student
where Sdept=‘CS’
)and Sdept<>‘CS’

7.檢索學生的學號、姓名、學習課程名及課程成績。
T-SQL語句:
select Student.Sno,Sname,Cname,Grade
from Student,Course,SC
where Student.Sno=SC.Sno and Course.Cno=SC.Cno;
8.檢索選修3門以上課程的學生的學號、總成績。
T-SQL語句:
select Sno,SUM(Grade)‘總成績’
from SC
group by Sno
having COUNT()>=3
9.檢索多於2名學生選修的課程號及平均成績。
T-SQL語句:
select Cno,AVG(Grade)‘平均成績’
from SC
group by Cno
having COUNT(
)>=2
(二)流程控制語句
1.如果Student表中有20歲的學生,把該學生的學號,姓名和性別查詢出來,否則輸出“沒有20歲的學生”。寫出T-SQL語句:(使用if…else語句)
if exists(select *from Student where Sage=‘20’)
select Sno,Sname,Ssex
from Student
where Sage=20
else
print ‘沒有的學生’
2.使用While語句求1到100之間的累加和,輸出結果。寫出T-SQL語句:
declare @sum int,@count int
select @sum=0,@count=1
while @count<=100
begin
set @sum=@sum+@count
set @count=@count+1
end
print @sum
(三)用戶自定義函數的應用
定義一個用戶自定義函數Score_Rechange,將成績從百分制轉化爲五級記分制。將該用戶定義函數用在查詢每個學生的成績中,給出五級記分制的成績。寫出T-SQL語句:
create function Score_Rechange(@score tinyint)
returns char(10)
as
begin
return
case
when @score>=90 then’優秀’
when @score>=80 and @score<90 then’良好’
when @score>=70 and @score<80 then ‘中等’
when @score>=60 and @score<70 then’及格’
else ‘不及格’
end
end

select Student.Sno,Sname,dbo.Score_Rechange(Grade)‘五級’
from Student ,SC
where Student.Sno=SC.Sno

發佈了46 篇原創文章 · 獲贊 49 · 訪問量 6235
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章