用于获取特定行周围的行的SQL查询

时间:2013-07-29 07:43:18

标签: sql

我有比赛的桌面结构:

user_id | score

我需要获取2行之前的信息(例如)user_id = 20和显示排名表之后的2行。

我想要得分表的结果:

order | user_id | score
   23 | XY1     |   240
   24 | XY1     |   247
   25 | 20      |   250 (my specific row)
   26 | XY1     |   252
   27 | XY1     |   290

1 个答案:

答案 0 :(得分:1)

with aaa as
(
SELECT  
ROW_NUMBER() OVER (ORDER BY score ) AS 'ROW_NUMBER', score, user_id
)

select * from aaa where ROW_NUMBER between
(select ROW_NUMBER-2 from aaa where user_id = 25) AND
(select ROW_NUMBER+2 from aaa where user_id = 25)