打印玩家和他(她)邻居的等级

时间:2012-12-23 07:31:43

标签: sql sql-server database tsql

有一张桌子存储了每位玩家的最高分:

select * from TMP_TABLE

结果:

USERID     SCORE
---------- -----------
aaa         10
bbb         30
ccc         50
ddd         90
eee         80
fff         50
ggg         20
hhh         40
iii         50

(9 row(s) affected)

好的,现在我想显示每个球员的排名:

select *,r=rank() over(order by score desc) from TMP_TABLE 

结果

USERID     SCORE       r
---------- ----------- --------------------
ddd        90          1
eee        80          2
fff        50          3
ccc        50          3
iii        50          3
hhh        40          6
bbb        30          7
ggg        20          8
aaa        10          9

(9 row(s) affected)

现在我要打印用户'bbb'和他(她)邻居的名字和得分等级,如下所示:

USERID     SCORE       r
---------- ----------- --------------------
hhh        40          6
bbb        30          7
ggg        20          8
(3 row(s) affected)

但是,我无法弄清楚哪个查询语句显示了这个结果。当然,应该考虑处理性能。 请帮我。谢谢。

2 个答案:

答案 0 :(得分:3)

如果您的RDBMS支持Common Table Expression,这是我第一次尝试,

WITH ranking AS
(
  SELECT *,
         RANK() OVER (ORDER BY score DESC) userRank
  FROM   TableName  
)
SELECT *
FROM   ranking
WHERE  userRank BETWEEN
        (SELECT userRank - 1 FROM ranking WHERE userID = 'bbb') AND
        (SELECT userRank + 1 FROM ranking WHERE userID = 'bbb')

答案 1 :(得分:1)

还有一个选择

;WITH cte AS
 (
  SELECT *,
         RANK() OVER(ORDER BY score DESC) AS r,
         CASE WHEN USERID = 'bbb' THEN RANK() OVER(ORDER BY score DESC) - 1 END AS bRank,
         CASE WHEN USERID = 'bbb' THEN RANK() OVER(ORDER BY score DESC) + 1 END AS eRank
  FROM dbo.TMP_TABLE
  )
  SELECT USERID, SCORE, r
  FROM cte c
  WHERE USERID = 'bbb' OR EXISTS (SELECT 1 FROM cte WHERE c.r BETWEEN bRank AND eRank)

SQLFiddle上的演示

当hhh和bbb等于

时,可以使用最佳方式DENSE_RANK

SQLFiddle

上使用DENSE_RANK进行演示