首页 文章

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

提问于
浏览
0

我有一个名为 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 回答

  • 1

    根据您的描述,您似乎不需要嵌套聚合函数,count(不同项)构造将为您提供销售的不同项目的计数,如下所示:

    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的列(例如,如果表中的每个项目都有行,但销售可能包括三个小部件)

    select date_trunc('month', date) as month
     , count(distinct items) as unique_items_sold
     , sum(item_count) as total_items_sold
    from retail 
    group by "month" 
    order by "month" ;
    
  • 0

    使用子查询:

    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
            )
    
  • 0

    我怀疑你的 group by 语句会抛出 Error ,因为你的 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 ,然后在外部使 sum 进行操作 .

相关问题