2015-02-24 102 views
0

我在最後一個「高級選擇語句」的問題,並不能得到正確的答案。SQL Aggregate Count語句

表1:書蟲數據庫的模式。主鍵帶下劃線。有一些外鍵引用將表連接在一起;你可以使用這些與自然連接。

Author(aid, alastname, afirstname, acountry, aborn, adied). 
Book(bid, btitle, pid, bdate, bpages, bprice). 
City(cid, cname, cstate, ccountry). 
Publisher(pid, pname). 
Author_Book(aid, bid). 
Publisher_City(pid, cid). 

問題是......「找到寫過三本或更多本書的作者的名字。」

代碼工作,但我想要的所有作者名稱,而不是作者的ID ..

select count(aid) as authorBook, aid as authorName 
from Author_book natural join Author 
group by aid 
having count(aid) > 3; 

決賽桌出來作爲...

authorbook | authorname 
------------+------------ 
     8 | dick 
     4 | thar 
(2 rows) 
+0

您的查詢中需要作者和書籍表。加入或子選擇! – jarlh 2015-02-24 16:22:46

回答

2

你需要HAVING COUNT(aid) > 3不能使用別名authorBook。

那麼,如果你需要作者的名字和它的表,你可以這樣做:

SELECT AuthorName, COUNT(*) AS CountOfBooks FROM AuthorBooks GROUP BY AuthorName HAVING COUNT(*) > 3

如果作者的名字是一個外鍵做到這一點:

SELECT x.AuthorName, COUNT(x2.*) FROM 
AuthorBooks x2 INNER JOIN Authors x1 ON x1.AuthorID = x2.AuthorID 
GROUP BY x.AuthorName HAVING COUNT(x2.*) > 3 
+0

我試圖聯繫作者的名字。 – 2015-02-24 16:25:01

+0

@ZekeP,這就是爲什麼你需要在你的查詢作者表。嘗試加入,或者子選擇! – jarlh 2015-02-24 16:26:12

+0

ZekeP看到我的編輯。 – JonH 2015-02-24 16:28:05

0
SELECT A.alastname, 
     A.afirstname, 
     COUNT(*) as Books 
FROM Author_Book AB 
INNER JOIN Author A 
    ON AB.aid = A.aid 
GROUP BY aid 
HAVING COUNT(*) > 3