RowNumber在Count Case中不起作用

时间:2013-09-07 19:20:36

标签: tsql count sql-server-2008-r2 case row-number

我有这个来计算状态'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语句中包含行号时,它给出了错误的输出

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

1 个答案:

答案 0 :(得分: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

得到了正确的输出,但我遇到了新问题Row-Number in Between Sub Query