Question : SQL Sorting Issue

I have a question about retrieving a data-set using MS SQL Server 2008, and it's confusing me...

My data is (for example):

ResultID, Score, UserID
--------------------------------
2,50,63
3,55,82
7,100,23
9,20,24
10,35,62

(see code attachment for layout)

There are hundreds of rows of data.

I want to be able to pick a user, and display the 3 results above, and the 3 results below that user, sorted by score - a bit like a leaderboard, for a total of 7 results each time. I've tried using ROW_NUMBER to enumerate the rows, and pull out sections of the data, but I'm not having much luck!

Any ideas? Part of the complication is that if the user is top, I still want 7 results - so user at the top, and 6 results below. The same if the user is last - 6 results above the user, and the last being the user.

Code Snippet:
1:
2:
3:
4:
5:
6:
7:
ResultID, Score, UserID
--------------------------------
2          50        63
3          55        82
7          100       23
9          20        24
10         35        62

Answer : SQL Sorting Issue

This may not be the tidiest solution but it should work:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
DROP TABLE #Results
DECLARE @UserID int
SET @UserID = 10

select 
	*,
	ROW_NUMBER() OVER(ORDER BY Score DESC) AS RowNum
	INTO #Results
from result

DECLARE @UserNo int, @MinNum int, @MaxNum int
SELECT @UserNo = RowNum
	FROM #Results
	WHERE UserID = @UserID

SELECT @MinNum = CASE WHEN @UserNo > 3 THEN @UserNo - 3 ELSE @UserNo END
SELECT @MaxNum = @MinNum + 6

DECLARE @Diff int
SELECT @Diff = @MaxNum - MAX(RowNum)
	FROM #Results


SELECT @MaxNum = CASE WHEN @Diff > 0 THEN MAX(RowNum) ELSE @MaxNum END
	FROM #Results
SELECT @MinNum = CASE WHEN @Diff > 0 THEN @MinNum - @Diff ELSE @MinNum END


SELECT *
	FROM #Results
	WHERE RowNum >= @MinNum AND Rownum <= @MaxNum
Random Solutions  
 
programming4us programming4us