1. 程式人生 > >[轉載]編寫SQL語句查詢出每個各科班分數最高的同學的名字,班級名稱,課程名稱,分數

[轉載]編寫SQL語句查詢出每個各科班分數最高的同學的名字,班級名稱,課程名稱,分數

csdn cat eight microsoft lock ble where earch mar

[轉載]編寫SQL語句查詢出每個各科班分數最高的同學的名字,班級名稱,課程名稱,分數

轉載自:https://blog.csdn.net/one_money/article/details/5692120

有以下兩張表,
Class表
classid classname
1 高三(一)班
2 高三(二)班
3 高三(三)班
Student表
studentid studentName classid
1 張三 2
2 李四 1
3 王五 1
4 趙六 3
5 錢七 2
6 孫九 3
score表
scoreid course studentid score
1 數學 2 99
2 數學 3 60
3 數學 4 80
4 語文 5 79
5 語文 6 58
6 語文 1 66
7 英語 6 76
8 英語 4 87
9 英語 3 100
10 英語 2 69
編寫SQL語句查詢出每個各科班分數最高的同學的名字,班級名稱,課程名稱,分數

SQL語句:

if exists(select count(*) from sysobjects where type=‘U‘ and name=‘#temp‘)
drop table #temp
select p.studentid,studentname,p.classid,classname,course,score into #temp from
( select studentid,studentname,student.classid,classname
from student right outer join class on student.classid=class.classid) as p
left outer join score on p.studentid=score.studentid
select (select top 1 studentname from #temp where classname=x.classname and course=x.course order by score desc) as ‘姓名‘,classname as ‘班級‘,course as ‘課程‘,max(score) as ‘分數‘
from #temp x group by classname,course order by classname

編寫SQL語句查詢出每個各科班分數最高的同學的名字,班級名稱,課程名稱,分數

2010年06月24日 17:24:00 one_money 閱讀數:9041 標簽: sqljoinclasstable 個人分類: SQL Server

有以下兩張表,
Class表
classid classname
1 高三(一)班
2 高三(二)班
3 高三(三)班
Student表
studentid studentName classid
1 張三 2
2 李四 1
3 王五 1
4 趙六 3
5 錢七 2
6 孫九 3
score表
scoreid course studentid score
1 數學 2 99
2 數學 3 60
3 數學 4 80
4 語文 5 79
5 語文 6 58
6 語文 1 66
7 英語 6 76
8 英語 4 87
9 英語 3 100
10 英語 2 69
編寫SQL語句查詢出每個各科班分數最高的同學的名字,班級名稱,課程名稱,分數

SQL語句:

if exists(select count(*) from sysobjects where type=‘U‘ and name=‘#temp‘)
drop table #temp
select p.studentid,studentname,p.classid,classname,course,score into #temp from
( select studentid,studentname,student.classid,classname
from student right outer join class on student.classid=class.classid) as p
left outer join score on p.studentid=score.studentid
select (select top 1 studentname from #temp where classname=x.classname and course=x.course order by score desc) as ‘姓名‘,classname as ‘班級‘,course as ‘課程‘,max(score) as ‘分數‘
from #temp x group by classname,course order by classname

[轉載]編寫SQL語句查詢出每個各科班分數最高的同學的名字,班級名稱,課程名稱,分數