表结构如下:
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 desc2.
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结果如下:

人生没有回头路,珍惜当下。
    
    










