SQL server 复杂查询
文章目錄
- 1. 實驗目的
- 2.實驗內容
- 3.實驗環境
- 實驗步驟及結果
1. 實驗目的
? ? 通過本次實驗使學生掌握數據庫中表數據的各種復雜查詢操作。
2.實驗內容
3.實驗環境
實驗步驟及結果
Student 表
| S1 | WANG | 15 | 男 |
| S2 | LI | 17 | 女 |
| S3 | LU | 19 | 女 |
| S4 | ZHAO | 13 | 女 |
| S5 | YANG | 20 | 男 |
Course表
| C1 | Maths | T1 |
| C2 | DB | T2 |
| C3 | English | T3 |
| C4 | Computer | T2 |
| C5 | Chinese | T2 |
SC表
| S1 | C1 | 50 |
| S2 | C1 | 70 |
| S3 | C1 | 80 |
| S4 | C1 | 75 |
| S5 | C1 | 87 |
| S1 | C2 | |
| S2 | C2 | |
| S4 | C2 | 85 |
| S1 | C3 | |
| S5 | C4 | 60 |
| S4 | C4 | 45 |
Title表
| T1 | 吳恩達 | 教師 |
| T2 | 劉曉慶 | 教授 |
| T3 | 張龍 | 副教授 |
注明:表格和下面的代碼可能不會一一對應,可能需要增加,刪除,更改表中的數據
1、檢索年齡小于17的女學生的學號和年齡
select S#,snamefrom Studentwhere age<17 and Ssex='女'go2、檢索男學生所學課程的課程號和成績
select distinct Student.s#,scorefrom Student,scwhere Ssex='男'go3、檢索男學生所學課程的任課老師的工號和姓名
select distinct title.T#,Tnamefrom course,title,Student,scwhere course.t#=title.t# and Student.s#=sc.s# and course.C#=sc.c# and Student.Ssex='男'go4、檢索至少選修兩門課的學生學號
select distinct a.s#from sc a,sc bwhere a.s#=b.s# and a.c#<>b.c#go5、檢索至少有學號s2和s4學生選修的課程的課程號(兩種方法解決)
(1).select distinct a.c#from sc a,sc bwhere a.s#='s2' and b.s#='s4' and a.c#=b.c#go(2).select distinct C#from scwhere c# in(select c#from scwhere s#='s2' )and s#='s4'go6、檢索wang同學不學的課程的課程號
select distinct C#from cwhere C# not in ( select distinct c#from scwhere s# in(select s# from swhere sname='wang'))go7、統計有學生選修的課程門數。
select count(distinct course.c#) 選課人數from course,Student,scwhere Student.s#=sc.s# and sc.c#=course.c#go8、求選修C4課程的女學生的平均年齡。
select avg(AGE) 平均年齡 from Student, SC where Student.S#=SC.S# and SC.C#='C4' and Ssex='女'9、求LIU老師所授課程的每門課程的學生平均成績。
select course.c#,avg(score) 平均成績from sc,title,coursewhere title.t#=course.t# and course.c#=sc.c# and tname='劉曉慶'group by course.c# go10、統計每門課程的學生選修人數(超過1人的課程才統計)。要求輸出課程號和選修人數, 查詢結果按人數降序排列,若人數相同,按課程號升序排列。
select c#,count (s#) 人數from scgroup by c#having COUNT(*)>1order by 2 desc ,1? ? ? ? order by 2 desc ,1中的“2”和“1”代表SC表中的第二列和第一列,如果寫成C#,S#,編譯器會報錯。
11、檢索學號比WANG同學大,而年齡比他小的學生姓名
select snamefrom Studentwhere s#>all(select s#from Studentwhere sname='wang')and age<all(select agefrom Studentwhere sname='wang') go12、在SC中檢索成績為空值的學生學號和課程號。
select s#,c#from scwhere score is null go13、檢索姓名以L打頭的所有學生的姓名和年齡。
select sname,agefrom Studentwhere sname like 'l%' go14、 求年齡大于女同學平均年齡的男學生姓名和年齡。
select sname,agefrom Studentwhere Ssex='男'and age >(select avg (age)from Studentwhere Ssex='女') go? ? ? ? 我現在也是一名大三的學生,接觸SQL Server的時間并不是很長,里面的代碼難免會出錯誤,如果是引用數據錯誤,請讀者們自己修改一下自己的代碼,如果是我的語法和引用出錯誤,請大家給我在評論區留言,我看到并驗證成功后我會改正自己的代碼,寫這個的目的也是為了同行的朋友們有一個借鑒和參考。
總結
以上是生活随笔為你收集整理的SQL server 复杂查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 漫谈Commons-Collection
- 下一篇: 初识 Redis