Sql-Server

將結果限制為前 2 個排名行

  • May 14, 2019

在 SQL Server 2008 中,我RANK() OVER (PARTITION BY Col2 ORDER BY Col3 DESC)使用RANK. 但是我每個分區都有數百條記錄,所以我會從排名 1、2、3……999 中獲取值。但我只希望每個最多 2RANKsPARTITION

例子:

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。我該怎麼做呢?

您可以將原始查詢 usingrank()放入子查詢中,並用過濾結果的查詢包裝它。

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

引用自:https://dba.stackexchange.com/questions/15583