Skip to content Skip to sidebar Skip to footer

Row-Number In Between Sub Query

select row_number() over (order by BookTitle) AS Row, BookTitleID, BookTitle, CallNumber, FullName, count(case Status when 'OnShelf' then 1 else null end) AS Co

Solution 1:

select * from(
select 
   Row,
   BookTitleID, 
   BookTitle,
   CallNumber,
   FullName,
   CopiesOnShelves
from
(  
select 
       Book.BookTitleID,
       BookTitles.BookTitle,
       BookTitles.CallNumber,
       FullName = LastName + ', ' + FirstName + ' ' + MiddleName,
       CopiesOnShelves = count(case Status when 'OnShelf' then 1 else null end),  
       Row = row_number() over (order by BookTitle)  
From
    Book
        left outer join 
    BookTitles
        on BookTitles.BookTitleID = Book.BookTitleID 
        left outer join
    Authors
        on Authors.AuthorID = BookTitles.AuthorID   

 Group By Book.BookTitleID, BookTitles.BookTitle, BookTitles.CallNumber, 
    LastName, FirstName, MiddleName
) sub
) sub2
WHERE Row between @start and @end

Solution 2:

Your row_Number function needs to be in the subquery. You cannot reference a row_number column in the where clause of the query where it is declared. You can from the outer query though. Just one of those weird TSQL rules. I wan't sure if you really wanted the row in the select results or not so I threw it in there anyway.

select 
   Row,
   BookTitleID, 
   BookTitle,
   CallNumber,
   FullName,
   count(case Status when 'OnShelf' then 1 else null end) AS CopiesOnShelves

from
(  
select 
       Book.BookTitleID,
       BookTitles.BookTitle,
       BookTitles.CallNumber,
       Book.Status,
       FullName = LastName + ', ' + FirstName + ' ' + MiddleName,
       row_number() over (order by BookTitle) AS Row

From
    Book
        left outer join 
    BookTitles
        on BookTitles.BookTitleID = Book.BookTitleID 
        left outer join
    Authors
        on Authors.AuthorID = BookTitles.AuthorID   ) sub
Where Row between 1 and 10 -- not working
Group By Callnumber, BookTitle, BookTitleID, FullName, Row

Post a Comment for "Row-Number In Between Sub Query"