将结果限制在前2个排名行中


22

在SQL Server 2008中,我RANK() OVER (PARTITION BY Col2 ORDER BY Col3 DESC)用来返回带有的数据集RANK。但是我每个分区都有数百条记录,因此我将从1、2、3 ...... 999列中获取值。但我只希望RANKs每个最多2 个PARTITION

例:

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。我该怎么做呢?

Answers:


15

您可以将原始查询使用rank()放入子查询中,并用过滤结果的查询进行包装。


说得通。我希望Microsoft可以使其更加简单,即在RANK函数中添加一个数字。RANK(2) OVER (PARTITION BY Col2 ORDER B Y Col3) AS Top_2_Ranks。可能会在将来的版本中发生。谢谢你的主意。
UB01 2012年

@ UB01:或者更好的是,最好在WHERE子句中使用窗口函数。
所有行业的乔恩(Jon of All Trades)

16
select * from (
SELECT Subject, Name, RANK() OVER (PARTITION BY Subject ORDER BY Score DESC) as RN
FROM Table
) a
where a.RN <= 2

0

我认为在SQL Server中执行此操作的方法是将窗口函数与常见的表表达式结合在一起:

with cte as (
SELECT Subject, Name, RANK() OVER (PARTITION BY Subject ORDER BY Score DESC) as ordinal
FROM Table
)
select * from cte where ordinal <= 2

-1

对于Teradara,您也可以执行以下操作:

SELECT 
Subject, 
Name, 
RANK() OVER (PARTITION BY Subject ORDER BY Score DESC) as RN
FROM Table
QUALIFY a.RN <= 2

3
好吧,那也许没问题,但是问题特别是关于SQL Server。
dezso
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.