專業(yè)試題:計算機(jī)考試關(guān)系數(shù)據(jù)庫標(biāo)準(zhǔn)語言--SQL
公務(wù)員考試專用訓(xùn)練軟件《公務(wù)員考試百寶箱》1.0版
對于下述3個關(guān)系:
S (S#, Sn, Sa, Sex)
C (C#, Cn, TEACHER)
SC (S#, C#, GRADE)
試用SQL的查詢語句表達(dá)下列查詢:
(1) 檢索LIU老師所授課程的課程號和課程名。
SELECT C#, Cn
FROM C
WHERE TEACHER=’LIU’
(2) 檢索年齡大于23歲的男學(xué)生的學(xué)號和姓名。
SELECT S#, Sn
FROM S
WHERE Sa>23 AND Sex=’男’
(3) 檢索學(xué)號為S3學(xué)生所學(xué)課程的課程名和任課老師。
方法一:
SELECT Cn, TEACHER
FROM C
WHERE C# IN
(SELECT C#
FROM SC
WHERE S#=’S3’)
方法二:
SELECT Cn, TEACHER
FROM C, SC
WHERE C.C#=SC.C# AND SC.S#=’S3’
方法三:
SELECT Cn, TEACHER
FROM C
WHERE EXISTS
(SELECT *
FROM SC
WHERE SC.C#=C.C# AND S#=’S3’)
公務(wù)員考試專用訓(xùn)練軟件《公務(wù)員考試百寶箱》1.0版
公務(wù)員考試專用訓(xùn)練軟件《公務(wù)員考試百寶箱》1.0版
(6) 檢索至少選修兩門課程的學(xué)生學(xué)號。
方法一:
SELECT DISTINCT S1.S#
FROM SC AS SC1, SC AS SC2
WHERE SC1.S#=SC2.S# AND SC1.C#!=SC2.C#
方法二:
SELECT S#
FROM SC
GROUP BY S#
HAVING COUNT(*)>=2
(7) 檢索全部學(xué)生都選修的課程的課程號和課程名。
方法一:
SELECT C#, Cn
FROM C
WHERE NOT EXISTS
(SELECT *
FROM S
WHERE NOT EXISTS
(SELECT *
FROM SC
WHERE SC.S#=S.S# AND SC.C#=C.C#)
)
方法二:
SELECT C#, Cn
FROM C
WHERE NOT EXISTS
(SELECT *
FROM S
WHERE S# NOT IN
(SELECT S#
FROM SC
WHERE SC.C#=C.C#)
方法三:
SELECT C#, Cn
FROM C
WHERE C# IN
(SELECT C#
FROM SC
GROUP BY C#
HAVING COUNT(*)=
(SELECT COUNT(*)
FROM S
)
公務(wù)員考試專用訓(xùn)練軟件《公務(wù)員考試百寶箱》1.0版
(8) 檢索選修課程中包含LIU老師所授課程的學(xué)生學(xué)號
方法一:
SELECT DISTINCT S#
FROM SC
WHERE C# IN
(SELECT C#
FROM C
WHERE TEACHER=’LIU’)
方法二:
SELECT DISTINCT S#
FROM SC
WHERE EXISTS
(SELECT *
FROM C
WHERE C.C#=SC.C# AND TEACHER=’LIU’)
方法三:
SELECT DISTINCT S#
FROM SC, C
WHERE SC.C#=C.C# AND C.TEACHER=’LIU’
10.試用SQL查詢語句表達(dá)下列對教學(xué)數(shù)據(jù)庫3個基本表S,C,SC的查詢.
S(S#, Sn, Sa, Sex)
C(C#, Cn, TEACHER)
SC(S#, C#, GRADE)
(1)在表C中統(tǒng)計開設(shè)課程的教師人數(shù).
(2)求選修C4課程的女學(xué)生的平均年齡.
(3)求每個學(xué)生都選修課程(已有成績)的門數(shù)和平均成績.
(4)統(tǒng)計每個學(xué)生選修課程的門數(shù)(超過5門的學(xué)生才統(tǒng)計).要求輸出學(xué)生學(xué)號和選修門數(shù),查詢結(jié)果按門數(shù)降序排列,若門數(shù)相同,按學(xué)號升序排列.
(5)檢索學(xué)號比WANG同學(xué)大,而年齡比他小的學(xué)生姓名.
(6)在表SC中檢索成績?yōu)榭罩档膶W(xué)生學(xué)號和課程號.
(7)檢索姓名以L開頭的所有學(xué)生的姓名和年齡.
(8)求年齡大于女同學(xué)平均年齡的男學(xué)生姓名和年齡.
(9)求年齡大于所有女同學(xué)年齡的男學(xué)生的姓名和年齡.
公務(wù)員考試專用訓(xùn)練軟件《公務(wù)員考試百寶箱》1.0版
參考答案:
(1)在表C中統(tǒng)計開設(shè)課程的教師人數(shù).
Select Count(distinct TEACHER)
from C
(2)求選修C4課程的女學(xué)生的平均年齡.
Select AVG(SA)
from S
where Sex=0 and S# in
(select S#
from SC
where C#='C4')
(3)求每個學(xué)生都選修課程(已有成績)的門數(shù)和平均成績.
Select S#, AVG(GRADE), COUNT(C#)
from SC
Group by S#
(4)統(tǒng)計每個學(xué)生選修課程的門數(shù)(超過5門的學(xué)生才統(tǒng)計).要求輸出學(xué)生學(xué)號和選修門數(shù),查詢結(jié)果按門數(shù)降序排列,若門數(shù)相同,按學(xué)號升序排列.
Select COUNT(C#), S#
from SC
GROUP BY S#
HAVING COUNT(*)>5
ORDER BY COUNT(*) DESC, SC.S# ASC
(5)檢索學(xué)號比WANG同學(xué)大,而年齡比他小的學(xué)生姓名.
方法一:
Select Sn
from S
where S.S#>(select S1.S#
from S as S1
where S1.Sn='WANG')
and S.Sa< ( select S2.Sa
from S as S2
where S2.Sn='WANG')
方法二:
Select Sn
from S as S1
where Exists (select *
from S as S2
where S2.Sn='WANG') and S1.S#>S2.S#
and S1.Sa