1. 程式人生 > >SQL server 複雜查詢

SQL server 複雜查詢

文章目錄

1. 實驗目的

    通過本次實驗使學生掌握資料庫中表資料的各種複雜查詢操作。

2.實驗內容

  1. 連線查詢
  2. 巢狀查詢
  3. 謂詞查詢

3.實驗環境

  1. Windows
  2. SQL Server

實驗步驟及結果

  1. 建立一個數據庫,檔名為“教學”
  2. 開啟“教學”資料庫

Student 表

S# Sname Age Ssex
S1 WANG 15
S2 LI 17
S3 LU 19
S4 ZHAO 13
S5 YANG 20

Course表

C# Cname T#
C1 Maths T1
C2 DB T2
C3 English T3
C4 Computer T2
C5 Chinese T2

SC表

S# C# Score
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表

T# Tname Title
T1 吳恩達 教師
T2 劉曉慶 教授
T3 張龍 副教授

註明:表格和下面的程式碼可能不會一一對應,可能需要增加,刪除,更改表中的資料

  1. 輸入如下資料:

1、檢索年齡小於17的女學生的學號和年齡

    select S#,sname
    	from Student
    	where age<17 and Ssex='女'
    go

2、檢索男學生所學課程的課程號和成績

    select distinct Student.s#,score
    	from Student,sc
    	where Ssex='男'
    go

3、檢索男學生所學課程的任課老師的工號和姓名

    select distinct title.T#,Tname
    	from course,title,Student,sc
    	where course.t#=title.t# and 
    		Student.s#=sc.s# and course.C#=sc.c# 
    		and Student.Ssex='男'
    go

4、檢索至少選修兩門課的學生學號

    select distinct a.s#
    	from sc a,sc b
    	where a.s#=b.s# and a.c#<>b.c#
    go

5、檢索至少有學號s2和s4學生選修的課程的課程號(兩種方法解決)

    (1).
    select distinct a.c#
    	from sc a,sc b
    	where a.s#='s2' and b.s#='s4' and a.c#=b.c#
    go

    (2).
    select distinct C#
    	from sc
    	where c# 
    	in(
    		select c#
    		from sc
    		where s#='s2' )
    		and s#='s4'
    go

6、檢索wang同學不學的課程的課程號

    select distinct C#
    	from c
    	where C# not in (		
    		select distinct c#
    			from sc
    			where s# in(
    			select s# 
    				from s
    				where sname='wang'))
	go

7、統計有學生選修的課程門數。

    select count(distinct course.c#) 選課人數
    	from course,Student,sc
    	where Student.s#=sc.s# and sc.c#=course.c#
    go

8、求選修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,course
	where title.t#=course.t# and course.c#=sc.c# and tname='劉曉慶'
	group by course.c#
go

10、統計每門課程的學生選修人數(超過1人的課程才統計)。要求輸出課程號和選修人數, 查詢結果按人數降序排列,若人數相同,按課程號升序排列。

select c#,count (s#) 人數
	from sc
	group by c#
	having COUNT(*)>1
	order by 2 desc ,1

        order by 2 desc ,1中的“2”和“1”代表SC表中的第二列和第一列,如果寫成C#,S#,編譯器會報錯。

11、檢索學號比WANG同學大,而年齡比他小的學生姓名

select sname
	from Student
	where s#>all(select s#
		from Student
		where sname='wang')
		and age<all(select age
			from Student
			where sname='wang')
go

12、在SC中檢索成績為空值的學生學號和課程號。

select s#,c#
	from sc
	where score is null
go

13、檢索姓名以L打頭的所有學生的姓名和年齡。

select sname,age
	from Student
	where sname like 'l%'
go

14、 求年齡大於女同學平均年齡的男學生姓名和年齡。

select sname,age
	from Student
	where  Ssex='男'and age >(
	select avg (age)
		from Student
		where Ssex='女')
go

        我現在也是一名大三的學生,接觸SQL Server的時間並不是很長,裡面的程式碼難免會出錯誤,如果是引用資料錯誤,請讀者們自己修改一下自己的程式碼,如果是我的語法和引用出錯誤,請大家給我在評論區留言,我看到並驗證成功後我會改正自己的程式碼,寫這個的目的也是為了同行的朋友們有一個借鑑和參考。