Kumar Gaurav
Kumar Gaurav

Reputation: 939

Unable to select 'n' records in each item category with paging

I am trying to select 5 records in each ItemCategoryID with paging, with the query below I am able to get 5 records in each category but paging is not working, as i have declared page size 10, but i am getting 19 records and @ItemCounter TotalCount is coming as 45... i m not getting how to solve it..here is the query:

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

Thanks in advance.

Upvotes: 0

Views: 112

Answers (1)

Remus Rusanu
Remus Rusanu

Reputation: 294387

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

What exactly do you expect from this? the row number has to be between start and end AND it has to be less than or equal to 3? What is start is 4? Any End above 3 is irrelevant.

I'm going to make a leap of faith here and say that the correctly stated requirement for your problem is:

  • for each item category, return at most 4 auctions where status = 1
  • page the result

so you obviously have two counters to consider, one for auctions within category and one for paging:

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;

Performance will be likely bad, but nobody can design any performance w/o data schema knowledge (table definition, indexes etc) which are missing from the problem statement.

TotalRecordCount:

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;

Upvotes: 2

Related Questions