2014-01-22 85 views
0

嗨,有人可以幫我解決這個問題。我花了年齡試圖找出什麼我做錯了,但沒有運氣SQL多表查詢

  1. 出版商(PUBLISHERNAME,位置,noOftitles)
  2. 作者(名稱,位置)
  3. 書(書名,ISBN,成本,AUTHORNAME,PUBLISHERNAME)

問題

編寫一條SQL命令,以針對具有多個作者的每個發佈者,發佈者的名稱,發佈者的位置以及發佈者銷售的圖書的平均成本顯示。

代碼:

SELECT Book.publishername, location, avg(cost) 
FROM Publisher 
,  Book 
WHERE Publisher.publisherName = Book.publisherName 
GROUP 
BY  publisherName 
HAVING COUNT (DISTINCT authorname) >1 

錯誤

ORA-00918:列定義的含糊

正確答案:

SELECT Publisher.publisherName, Publisher.location, avg(cost) 
FROM Publisher, Book 
WHERE Publisher.publisherName = Book.publisherName 
GROUP BY Publisher.PublisherName, Publisher.Location 
HAVING COUNT (DISTINCT authorname) >1; 
+1

您使用的是什麼RDBMS?這是功課嗎? – Dan

+0

@丹。看起來像Oracle,從錯誤代碼。 – Shiva

+1

@Shiva那簡單明瞭就顯得太有道理了。 :) – Dan

回答

1

您的選擇中有不明確的列名。 select語句中的location可能來自Publisher表或Author表,並且GROUP BY中的publisherName可能來自Publisher或Book。您需要明確指定要從哪些表中獲取這些值。

SELECT Book.publishername, Publisher.location, avg(cost) 
FROM Publisher, Book 
WHERE Publisher.publisherName =Book.publisherName 
GROUP BY publisher.publisherName 
HAVING COUNT (DISTINCT authorname) >1; 

編輯:關於你的評論,你有你的選擇列,要麼是沒有在GROUP BY或一個非集合函數(如SUM,AVG等)。您需要包括location在GROUP BY:

SELECT Book.publishername, Publisher.location, avg(cost) 
FROM Publisher, Book 
WHERE Publisher.publisherName =Book.publisherName 
GROUP BY publisher.publisherName, Publisher.location 
HAVING COUNT (DISTINCT authorname) >1; 
+0

我試過這個^^^,但給我一個錯誤說:\t ORA-00979:不是GROUP BY表達式 – user2993831

+0

@ user2993831這是由於「位置」列。看看我的編輯。 –

+1

仍然沒有運氣:( – user2993831

0

它不應該是GROUP BY Book.publisherName?

0

位置在兩個表中。您可以通過使用TABLE.COLUMN來定義它:

Publisher.location 
0

你GROUP BY應該讀 GROUP BY Book.publishername

0

答案並解釋是怎麼回事。以下是您的查詢:

SELECT Book.publishername, location, avg(cost) 
FROM Publisher, Book 
WHERE Publisher.publisherName =Book.publisherName 
GROUP BY publisherName 
---------^ 
HAVING COUNT (DISTINCT authorname) >1; 

Oracle不知道列的來源。它可以來自任何一個表格。所以,用表別名前綴所有列。此外,請使用正確的連接語法,而不是隱式連接。這裏是你的查詢的更好的版本:

SELECT b.publishername, p.location, avg(b.cost) 
FROM Publisher p join 
    Book b 
    on p.publisherName = b.publisherName 
GROUP BY b.publisherName 
HAVING COUNT(DISTINCT b.authorname) > 1; 

我想在表的列從哪裏來。