基于ID的SQL偏移量

时间:2014-09-11 09:49:53

标签: sql sql-server offset

尝试根据用户ID找到3行。

结果应该与当前用户以及之前和之后的行抵消:

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?

1 个答案:

答案 0 :(得分: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