我有一个名为 retail
的表,它存储 items
和他们的 price
以及 date
的购买 . 我想找出 total monthly count of unique items sold .
这是我试过的SQL查询
select date_trunc('month', date) as month, sum(count(distinct(items))) as net_result from retail group by month order by date;
但是我收到以下错误
ERROR: aggregate function calls cannot be nested
现在我搜索了类似的stackoverflow帖子,其中一个是postgres aggregate function calls may not be nested但我无法复制它来创建正确的SQL查询 .
我究竟做错了什么?
3 回答
根据您的描述,您似乎不需要嵌套聚合函数,count(不同项)构造将为您提供销售的不同项目的计数,如下所示:
如果您有一个名为item_count的列(例如,如果表中的每个项目都有行,但销售可能包括三个小部件)
使用子查询:
我怀疑你的
group by
语句会抛出Error
,因为你的month
列是条件列,你不能在查询中放入相同的级别,所以请改为使用完整的表达式 .您不能创建嵌套聚合,因此首先将
count
包装到subquery
,然后在外部使sum
进行操作 .