我有一个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))
(需要计算差异)在同一结果中使用两者都会给我带来问题使用嵌套的聚合函数。
答案 0 :(得分:3)
您可以使用聚合函数的组合(计算每位艺术家的歌曲数量)和窗口函数来生成此结果:
SELECT artist,
COUNT(*) AS num_songs,
MAX(COUNT(*)) OVER (ORDER BY COUNT(*) DESC) - COUNT(*) AS diff
FROM artists
GROUP BY artist;
这有点笨拙,但它就是诀窍。
编辑:
正如@a_horse_with_no_name所评论的那样,order by
子句中的over
子句是多余的。删除它肯定会使代码更容易阅读:
SELECT artist,
COUNT(*) AS num_songs,
MAX(COUNT(*)) OVER () - COUNT(*) AS diff
FROM artists
GROUP BY artist;