Row-Number in Between Sub Query

…衆ロ難τιáo~ 提交于 2019-12-11 18:03:20

问题


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

How I will use In between ROW in this on example to display Row 1 to Row 10.


回答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



回答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


来源:https://stackoverflow.com/questions/18677361/row-number-in-between-sub-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!