取出一个成绩表中每科成绩最好的前两名(自联接和with as)

表结构如下:

1 CREATE TABLE [dbo].[stuScore](
2  [Id] [int] IDENTITY(1,1) NOT NULL,
3  [stuId] [int] NOT NULL,
4  [stuName] [nvarchar](255) NOT NULL,
5  [subject] [nvarchar](255) NOT NULL,
6  [score] [int] NOT NULL
7 ) ON [PRIMARY]

三种方法:

1.

1 select * from stuScore A where A.stuId in
2     (select top 2 stuId from stuScore B where A.subject=B.subject order by B.score desc)
3         order by A.score desc

2.

1 select * from stuScore A where 
2   (select COUNT(*) from stuScore B where A.subject = B.subject and B.score>=A.score)<=2
3   order by A.score desc

这两种方法查询结果不会按照科目分组:

3.利用with as

1 with cte as 
2 (
3     select *,rn=row_number() over(partition by subject order by score desc )
4     from stuScore 
5 )
6 select Id,stuId,stuName,subject,score from cte where rn<=2

结果如下:

posted @ 2014-02-13 16:31  风的姿态  阅读(470)  评论(0编辑  收藏  举报