Postgresql 如何在sql查询中包含三个或更多聚合器?

Postgresql 如何在sql查询中包含三个或更多聚合器?,postgresql,aggregate-functions,Postgresql,Aggregate Functions,我有一个名为retail的表,它存储项目及其价格以及购买日期。我想了解每月售出的独特物品的总数 这是我尝试的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

我有一个名为
retail
的表,它存储
项目
及其
价格
以及
购买日期。我想了解每月售出的独特物品的总数

这是我尝试的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帖子,其中一篇是,但我无法复制它来创建正确的sql查询

我做错了什么?

使用子查询:

Select month, sum(citems) as net_result 
   from 
       (select 
           date_trunc('month', date) as month, 
           count(distinct(items)) as citems 
        from 
           retail 
        group by month 
        order by date
        )

根据您的描述,似乎不需要嵌套聚合函数,count(distinct item)构造将为您提供已售出的不同商品的计数,如下所示:

select date_trunc('month', date) as month
 , count(distinct items) as unique_items_sold
 , count(items) as total_items_sold
from retail 
group by "month" 
order by "month" ;
如果您有一个名为item_count的列(假设表中每售出一件商品都有一行,但一次销售可能包括三个小部件)


我怀疑您的
groupby
语句将抛出一个
错误
,因为您的
month
列是条件列,您无法在查询中放入相同级别,因此请使用完整表达式

select
  month,
  sum(disct_item) as net_results
from
  (select 
     date_trunc('month', date) as month, 
     count(distinct items) as disct_item
   from 
     retail 
   group by 
     date_trunc('month', date)
   order by 
     date) as tbl
group by
  month;

您无法进行嵌套聚合,因此首先将
count
包装到
subquery
中,然后在outer中进行
sum
以执行该操作。

是的,这就是我需要的!
select
  month,
  sum(disct_item) as net_results
from
  (select 
     date_trunc('month', date) as month, 
     count(distinct items) as disct_item
   from 
     retail 
   group by 
     date_trunc('month', date)
   order by 
     date) as tbl
group by
  month;