每一个班级中每一门课程获得最高分的学生的学号

学生(学号,姓名,班级代号)
课程(课程号,课程名称,学分数)
成绩(学号,课程号,成绩)

CREATE TABLE [dbo].[Class](
 [ClassID] [int] NULL,
 [ClassName] [nvarchar](10) NULL
) ON [PRIMARY]

1 一班
2 二班
3 三班
CREATE TABLE [dbo].[Student](
 [StudentID] [nvarchar](10) NULL,
 [StudentName] [nvarchar](50) NULL,
 [ClassID] [int] NULL
) ON [PRIMARY]

2009001 小宋 1
2009002 小李 1
2009003 小王 2
2009004 小张 2
2009005 小孙 3
2009006 小雪 3

CREATE TABLE [dbo].[Score](
 [ID] [int] NOT NULL,
 [Score] [int] NULL,
 [Subject] [nvarchar](10) NULL,
 [StudentID] [nvarchar](10) NULL
) ON [PRIMARY]
1 20 数学 2009001
2 21 数学 2009002
3 6 数学 2009003
4 2 数学 2009004
5 8 数学 2009005
6 45 数学 2009006
7 68 语文 2009001
8 72 语文 2009002
9 35 语文 2009003
10 15 语文 2009004
11 85 语文 2009005
12 21 语文 2009006
13 22 科学 2009001
14 56 科学 2009002
15 54 科学 2009003
16 21 科学 2009004
17 35 科学 2009005
18 25 科学 2009006

方式一:
select  t1.hscore,t1.subject,t1.classid,t2.classname,t3.studentid from
(select MAX(A.score) HScore,A.Subject,B.ClassID from Score A inner join Student b on A.StudentID =b.StudentID group by A.Subject,B.classid) t1
inner join Class t2
on t1.ClassID=t2.ClassID
inner join score t3  on t1.Subject=t3.Subject and t1.HScore=t3.Score
inner join Student t4 on t3.StudentID=t4.StudentID
order by t2.ClassName,t1.Subject
方式二:
SELECT * FROM (
        SELECT ROW_NUMBER() OVER(PARTITION BY b.subject, a.classid ORDER BY b.subject, a.classid, b.score DESC) AS RN
               , b.subject, b.score,b.studentid, a.StudentName,a.classid
        FROM Student a INNER JOIN score b ON a.StudentID = b.StudentID) A
WHERE RN = 1

posted @ 2013-10-18 22:16  dennys  阅读(674)  评论(0编辑  收藏  举报