2014-09-11 62 views
0

嘗試根據用戶標識查找3行。基於ID的SQL偏移量

87. John Snow 1000p 
88. YOU 990p 
89. Jane Doe 900p 

我已經存儲在@currentUser用戶變量和使用下面的查詢,該查詢獲取所有有關的行動:

結果應與當前用戶和行之前和之後所抵消

SELECT u.UserID, 
     u.ContentID, 
     (u.FirstName + ' ' + u.LastName) AS theUser, 
     SUM(l.Action) as thePoints 
FROM [AccessLog] l 
     LEFT JOIN [User] u 
      ON l.UserID = u.UserID 
WHERE l.Action = 13 
     OR l.Action = 2 
     AND l.Timestamp BETWEEN CONVERT(datetime, '2014-09-01') AND CONVERT(datetime, '2014-09-11') 
GROUP BY u.UserID, 
     u.ContentID, 
     u.FirstName, 
     u.LastName 
ORDER BY thePoints DESC 

我將如何去列出例如。 #87到#89如果我的地方是#88?

+0

你在說用戶名的? – Azar 2014-09-11 09:51:42

+0

基於非標準語法添加SQL Server – 2014-09-11 09:52:44

回答

1

你應該看看OFFSETFETCH FIRST,但我相信它取決於你使用的數據庫版本。

SELECT u.UserID, 
     u.ContentID, 
     (u.FirstName + ' ' + u.LastName) AS theUser, 
     SUM(l.Action) as thePoints 
FROM [AccessLog] l 
     LEFT JOIN [User] u 
      ON l.UserID = u.UserID 
WHERE l.Action = 13 
     OR l.Action = 2 
     AND l.Timestamp BETWEEN CONVERT(datetime, '2014-09-01') AND CONVERT(datetime, '2014-09-11') 
GROUP BY u.UserID, 
     u.ContentID, 
     u.FirstName, 
     u.LastName 
ORDER BY thePoints DESC 
offset 87 rows 
fetch first 3 rows only 
+0

如果在查詢運行之前未知位置。這將如何成爲可能?用戶可以位於7或87. – 2mas 2014-09-11 11:16:09

+0

您可以創建一個參數「@ position」並用提供的人員的位置填充該參數,然後將「OFFSET 87 ROWS」更改爲「OFFSET(@position - 1 )行「 – talegna 2014-09-11 13:30:51