0

我有这个来计算状态为“OnShelf”的书的数量

select 

   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

Group By Callnumber, BookTitle, BookTitleID, FullName

样本输出

BookTitleID    BookTitle      CallNumber    Fullname   CopiesOnShelves
1              sample         test          test       3

但是当我在选择语句中包含行号时,它给了我错误的输出

select 

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

) sub

Group By Callnumber, BookTitle, BookTitleID, FullName, r

样本输出

BookTitleID    BookTitle      CallNumber    Fullname   CopiesOnShelves  R
1              sample         test          test       1                1
1              sample         test          test       1                2
1              sample         test          test       1                3
4

1 回答 1

0
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
Group By Callnumber, BookTitle, BookTitleID, FullName

得到了正确的输出,但我在子查询之间遇到了新问题行号

于 2013-09-07T20:15:44.077 回答