2015-02-24 87 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