2013-10-20 50 views
0

這可能是一個簡單的語法錯誤,但我一直在看它一個小時,我只是無法找到它,也許另一組眼睛可以幫助指向我在正確的方向?SQL Server 2012,嵌套select語句,語法錯誤?我沒有看到它

select 
    lname +', '+ Fname as "Author Name" 
from 
    Author a 
join 
    BOOKAUTHOR ba on a.AuthorID = ba.authorid 
where 
    ba.isbn = (select ba.isbn 
       from 
        (select 
         ROW_NUMBER() over (order by sum(quantity) desc) as "Placement", 
         b.isbn, 
         sum(QUANTITY) as "Total" 
        from 
         ORDERITEMS oi 
        join 
         Books b on b.ISBN = oi.isbn 
        group by 
         b.ISBN) 
       where Placement = 1) --the "WHERE" is giving me an error. 

回答

4

當你的FROM子句指定派生表爲表源,你必須給子查詢的別名:

select lname +', '+ Fname as "Author Name" 
from Author a 
join BOOKAUTHOR ba on 
a.AuthorID = ba.authorid 
where ba.isbn = 
     (select q.isbn -- <== notice the "q" 
     from 
      (select ROW_NUMBER() 
      over (order by sum(quantity) desc) as "Placement", 
      b.isbn, 
      sum(QUANTITY) as "Total" 
      from ORDERITEMS oi 
      join Books b 
      on b.ISBN = oi.isbn 
      group by b.ISBN) q -- <== notice the "q" 
     where Placement = 1) 

MSDN Library documentation

[ FROM { <table_source> } [ ,...n ] ] 
<table_source> ::= 
{ 
    ... 
    | derived_table [ AS ] table_alias [ (column_alias [ ,...n ]) ] 
    ... 
} 
+0

AKA,別名派生表,就像邁克爾說的那樣。 – Jace

+0

查詢的外部部分期望將其稱爲'ba' – Laurence

+0

在外部查詢中,我將'ba.isbn'更改爲'q.isbn',以避免混淆。 –