在sql Server 2008中,我使用RANK()OVER(PARTITION BY Col2 ORDER BY Col3 DESC)来返回带有RANK的数据集.但是我为每个分区都有数百条记录,因此我将获得1,2,3 …… 999等级的值.但是我想在每个PARTITION中最多只有2个RANK.
例:
ID Name score Subject 1 Joe 100 Math 2 Jim 99 Math 3 Tim 98 Math 4 Joe 99 History 5 Jim 100 History 6 Tim 89 History 7 Joe 80 Geography 8 Tim 100 Geography 9 Jim 99 Geography
我希望结果如下:
SELECT Subject,Name,RANK() OVER (PARTITION BY Subject ORDER BY score DESC) FROM Table
Subject Name Rank Math Joe 1 Math Jim 2 History Jim 1 History Joe 2 Geography Tim 1 Geography Jim 2
我只想在每个类别中排名第1和第2.我该怎么做呢?