2015-02-24 452 views
-1

表1:书虫数据库的模式。主键带下划线。有一些外键引用将表连接在一起;你可以使用这些与自然连接。带有DISTINCT语句的SQL SUM聚合

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). 

这个问题让我有点困惑,任何帮助都非常感谢。

查找每个国家/地区的作者数量。

到目前为止,我已经尝试

SELECT 
    SUM(DISTINCT acountry) AS total, 
    COUNT(DISTINCT acountry)AS N 
FROM Author; 

并得到:

ERROR: function sum(character varying) does not exist LINE 1: select sum(distinct acountry) as total, count(distinct acoun...

提示:无功能的指定名称和参数类型相匹配。您可能需要添加显式类型转换。

+0

您不能“求和”字符串。你认为“Arthur”和“Zaphod”的“总和”是什么?你想解决什么问题? – 2015-02-24 07:24:35

+0

好的,现在我明白了,谢谢。如何使用count语句呢? @a_horse_with_no_name。 – 2015-02-24 07:27:10

+0

您需要使用具有集合函数的'group' – 2015-02-24 07:28:44

回答

1

您不能sum字符串。由于acountry包含字符串值(假设国家/地区名称)。而要获得the number of authors of each country.得到你需要使用GroupBy国名和计数该组中的行,你可以试试下面这个国家明智的作家计数,

SELECT COUNT(*) AS totalAuthor, 
     acountry AS Country 
FROM Author 
GROUP BY acountry 
+0

谢谢!我知道我将不得不使用count而不是sum我不知道我为什么总是想。我明白为什么GroupBy被卷入,现在是有道理的。..祝贺 – 2015-02-24 07:38:14

+0

@a_horse_with_no_name没有那样的。只需输入它的匆忙。我会把它改成'*'。 – 2015-02-24 07:55:54

0

您可以通过国家需要组,计每组的记录数

SELECT acountry, COUNT(1) as NumberOfAuthors FROM Author GROUP BY acountry