子查询之间的行号

时间:2013-09-07 20:00:02

标签: tsql sql-server-2008-r2

select 
   row_number() over (order by BookTitle) AS 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

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

我将如何使用In在这个示例中的ROW之间显示第1行到第10行。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您的row_Number函数需要位于子查询中。您不能在声明它的查询的where子句中引用row_number列。你可以从外部查询。只是其中一个奇怪的TSQL规则。我不确定你是否真的想要选择结果中的那一行,所以无论如何我把它扔在那里。

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