SQL:多个嵌套聚合函数

SQL:多个嵌套聚合函数,sql,postgresql,select,aggregate-functions,Sql,Postgresql,Select,Aggregate Functions,我有一个PostgreSQL表,如下所示: artists | songs =================== artist1 | song a artist1 | song b artist2 | song c 我想做一个选择性的陈述,给我每个艺术家的曲目数量,以及他的曲目数量和拥有最多曲目的艺术家数量之间的差异 所以在这种情况下 artist | number songs | difference ==================================== arti

我有一个PostgreSQL表,如下所示:

artists | songs  
===================
artist1 | song a
artist1 | song b
artist2 | song c
我想做一个选择性的陈述,给我每个艺术家的曲目数量,以及他的曲目数量和拥有最多曲目的艺术家数量之间的差异

所以在这种情况下

artist  | number songs | difference
====================================
artist1 | 2            | 0
artist2 | 1            | 1

我遇到的问题是,我使用
count(songs)
来计算歌曲的数量,也使用
max(count(songs))
(计算差异所需)来计算相同的结果,使用这两种方法会给嵌套聚合函数带来问题。

您可以使用聚合函数的组合(计算每个艺术家的歌曲数)和窗口函数以产生此结果:

SELECT   artist, 
         COUNT(*) AS num_songs, 
         MAX(COUNT(*)) OVER (ORDER BY COUNT(*) DESC) - COUNT(*) AS diff
FROM     artists                                                       
GROUP BY artist;
这有点笨重,但它确实起作用了

编辑:
正如@a_horse_和_no_name所评论的那样,
over
子句中的
order by
子句是多余的。删除它肯定会使代码更易于阅读:

SELECT   artist, 
         COUNT(*) AS num_songs, 
         MAX(COUNT(*)) OVER () - COUNT(*) AS diff
FROM     artists                                                       
GROUP BY artist;