0

我正在尝试使用分页在每个 ItemCategoryID 中选择 5 条记录,通过下面的查询,我能够在每个类别中获得 5 条记录,但分页不起作用,因为我已声明页面大小为 10,但我得到 19 条记录和@ItemCounter TotalCount 即将达到 45 ......我不知道如何解决它..这是查询:

DECLARE @PageIndex int = 1
DECLARE @PageSize int = 10
DECLARE @StartRow int
DECLARE @EndRow int
SET @StartRow = (@PageSize * (@PageIndex - 1))  + 1  
SET @EndRow = @PageSize * @PageIndex + 1
DECLARE @ItemCounter int
SELECT @ItemCounter = Count(*)FROM dbo.Auctions WHERE AuctionStatus=1;
WITH Auctions AS
    (
        SELECT  ROW_NUMBER() OVER 
        (PARTITION BY ItemCategoryID  ORDER BY AuctionID) AS RowNumber,                 
            AuctionID, 
            ItemCategoryID  ,                             
            @ItemCounter TotalCount                         
            FROM Auctions                 
            WHERE                 
            AuctionStatus=1 
     )

    SELECT a.* FROM Auctions a  
    WHERE  a.RowNumber <=3 AND a.RowNumber 
    BETWEEN @StartRow AND @EndRow - 1

提前致谢。

4

1 回答 1

2
a.RowNumber <=3 AND a.RowNumber BETWEEN @StartRow AND @EndRow - 1

您对此有何期待?行号必须在开始和结束之间并且必须小于或等于 3?什么是开始是4?任何高于 3 的 End 都无关紧要。

我将在这里做出一个信念的飞跃,并说正确说明您的问题的要求是:

  • 对于每个物品类别,最多返回 4 次拍卖,其中 status = 1
  • 分页结果

所以你显然有两个计数器要考虑,一个用于类别内的拍卖,一个用于分页:

WITH Auctions AS
(
    SELECT  ROW_NUMBER() OVER 
    (PARTITION BY ItemCategoryID  ORDER BY AuctionID) AS AuctionNumber,                 
        AuctionID, 
        ItemCategoryID                             
        FROM Auctions                 
        WHERE                 
        AuctionStatus=1 
 ),
Paging as (
  SELECT ROW_NUMBER() OVER (ORDER BY ItemCategoryID, AuctionID) as RowNumber
   , a.* 
  FROM Auctions a  
  WHERE AuctionNumber <= 3 
)
SELECT * 
  FROM Paging 
  WHERE  RowNumber BETWEEN @StartRow AND @EndRow - 1;

性能可能会很差,但是没有人可以设计任何没有数据模式知识(表定义、索引等)的性能,而这些知识在问题陈述中是缺失的。

总记录数:

WITH Auctions AS
(
  SELECT  ROW_NUMBER() OVER 
    (PARTITION BY ItemCategoryID  ORDER BY AuctionID) AS AuctionNumber,                 
    AuctionID, 
    ItemCategoryID  ,                             
  FROM Auctions                 
  WHERE AuctionStatus=1 
)
SELECT @total = COUNT(*) 
 FROM Auctions a  
 WHERE AuctionNumber <= 3;
于 2012-09-12T07:12:07.147 回答