假設有一個表,SQL語句如下:
CREATE TABLE [dbo].[scan](
[km] [int] NULL,
[kh] [int] NULL,
[cj] [int] NULL
) ON [PRIMARY]
其中km為科目號、kh為考生號、cj為成績,現對km和kh進行分組,並獲得每組前2條記錄(按cj從高到低排序)。基本思想是為每組加一個序號列,再用where取序號小於等於2的。SQL語句如下:
select * from
(
select a.km,a.kh,cj,row_number() over(partition by a.km order by a.km,a.cj desc) n
from
(select km,kh,SUM(cj) cj from scan group by km,kh) a
) b where n<=2 order by km, cj desc
最後得到的結果集如下圖所示。