如何避免使用嵌套聚合函数?

时间:2018-05-31 10:53:13

标签: sql postgresql aggregate-functions

我需要一些帮助,我相信你们知道怎么做: 让我们从表结构开始:

author(name, nationality, Gender);
article(title, year, conference);
publication(articleTitle, authorName);

我需要了解出版物数量最多的作者的性别。按照我使用PostgreSQL的方式,不知道这是否重要。

这是我的想法:

select gender from author
join publication on(name = authorName)
having (count(articleTitle) = max(count(articleTitle)))
group by gender

现在,我知道我不能使用嵌套聚合函数,这就是我尝试使用嵌套选择的原因,例如select gender where gender in (another select)但是我没有设法避免聚合函数问题。 希望你能帮助我,谢谢你

1 个答案:

答案 0 :(得分:1)

此查询为您提供作者,按出版物数量排序:

select a.name, a.gender, count(*) as num_publications
from author a join
     publication p
     on a.name = p.authorName
group by a.name, a.gender
order by num_publications desc;

如果您想要前三名,请使用fetch firstlimit

select a.name, a.gender, count(*) as num_publications
from author a join
     publication p
     on a.name = p.authorName
group by a.name, a.gender
order by num_publications desc
fetch first 3 rows only;