使用Rank()时标记重复

时间:2017-05-18 22:12:49

标签: sql-server database

我正在准确地获得我想要使用的排名列表:

SELECT RANK() OVER(ORDER BY score) as rank, name, score FROM players

有没有办法在SQL中标记重复的排名?

例如,从中:

rank  name  score
----  ----  -----
 1     bob    98
 2     tom    96
 2     guy    96
 4     lou    92

到这个

rank  name  score
----  ----  -----
 1     bob    98
 T2    tom    96
 T2    guy    96
 4     lou    92

2 个答案:

答案 0 :(得分:1)

您可以执行类似

的操作
with q as
(
SELECT RANK() OVER(ORDER BY score) as rank, 
name, score 
FROM players
)
select *, count(*) over (partition by rank) players_at_rank
from q

rank                 name                 score       players_at_rank
-------------------- -------------------- ----------- ---------------
1                    alex                 2           1
2                    fred                 5           2
2                    joe                  5           2
4                    sue                  9           1

(4 row(s) affected)

答案 1 :(得分:0)

以下将标记所有重复的排名。它检查前一个或后一个条目是否具有相同的值。

SELECT RANK() OVER(ORDER BY score) as rank, name, score,
  IIF(LAG(score,1) OVER (ORDER BY score) = score OR LEAD(score,1) OVER (ORDER BY score) = score,1,0) as IsDuplicate
FROM players