我的用户表,表结构是:
ID UserName
1 AAA
4 BBB
7 CCC
........
........
其中ID是主键和标识字段。
假设PageSize为10,我想要find the page number for the ID 43
。有没有办法在哪个页面找到ID(43)?
谢谢!
答案 0 :(得分:1)
试试这个:
DECLARE @PageSize INT = 10
DECLARE @Order DECIMAL(10,2)
DECLARE @UserID INT = 1
SET @Order = ( SELECT OrderNo
FROM
(SELECT *, ROW_NUMBER() OVER (ORDER BY UserID) AS OrderNo
FROM Users
) AS U
WHERE U.UserID = @UserID
)
SELECT @UserID AS UserID, CEILING(@Order/@PageSize) PageNo
答案 1 :(得分:0)
您可以使用Row_Number分区选项来实现此目的。
SELECT ROW_NUMBER() OVER (ORDER BY UserID) AS OrderNo, *
FROM Users
现在你简单地给出页面大小的条件,找出页面号。在您的情况下,简单查询给出没有分区选项的结果。
Declare @userid int = 43, @PageSize int = 10
;with cte as
(
SELECT
ROW_NUMBER() OVER (ORDER BY UserID) AS OrderNo, *
FROM Users
)
Select
CEILING(OrderNo/@PageSize) PageNo
FROM
cte where userID = @UserID
Row_number with Partition选项。如果您想在另一列上重新订购,那么
;with cte as
(
SELECT
ROW_NUMBER() OVER (PARTITION BY CompanyId ORDER BY UserID ) AS OrderNo, *
FROM Users
)
Select
CEILING(OrderNo/@PageSize) PageNo
FROM
cte where userID = @UserID