【问题标题】:aggregate function calls cannot be nested postgresql聚合函数调用不能嵌套 postgresql
【发布时间】:2020-01-27 14:03:28
【问题描述】:

我从 PostgreSQL 收到“不能嵌套聚合函数调用”错误。我尝试了很多不同的东西,但无法解决。

select c.*, (
             select sum((count(distinct product_id))/2)
             from page_views
             where product_id in (c.p1, c.p2)
             group by user_id, session_id
             having count(distinct product_id) > 1
            ) freq
from (
      select a.product_id p1, b.product_id p2
      from (select distinct product_id from page_views) a,
           (select distinct product_id from page_views ) b
      where a.product_id <> b.product_id
     ) c ;

谢谢!

【问题讨论】:

  • 请解释您要做什么。无法正常运行的 SQL 不一定能很好地解释意图。
  • Edit您的问题并添加一些示例数据和基于该数据的预期输出。 Formatted textno screen shots

标签: sql postgresql


【解决方案1】:

您可以只使用 subselect 来获取嵌套的聚合函数,如下所示:

select c.*, (SELECT sum(count_column) FROM (
                 select (count(distinct product_id))/2 AS count_column
                 from page_views
                 where product_id in (c.p1, c.p2)
                 group by user_id, session_id
                 having count(distinct product_id) > 1
               ) sub_q
            ) freq
from (
      select a.product_id p1, b.product_id p2
      from (select distinct product_id from page_views) a,
           (select distinct product_id from page_views ) b
      where a.product_id <> b.product_id
     ) c ;

【讨论】:

    【解决方案2】:

    如果你想统计浏览过两个页面的用户,那么查询如下:

    select v1.product_id, v2.product_id, count(distinct v2.user_id)
    from page_views v1 join
         page_views v2
         on v1.user_id = v2.user_id and v1.session_id = v2.session_id and
            v1.product_id < v2.product_id
    group by v1.product_id, v2.product_id;
    

    这是我能想象到的对实际意图最合理的解释。

    【讨论】:

      【解决方案3】:

      我不完全理解您在这个示例中要做什么,但是我想展示一个示例,说明我如何在 PostgresQL 中使用多个聚合函数。

      假设我的目标是找到 max(time) - min(time) 的最大值:

      select max(a.trip_time) from 
      (  select trip_id, max(time) - min(time) as trip_time 
         from gps_data 
         where date = '2019-11-16' 
         group by trip_id) as a;
      

      我希望这很清楚!

      【讨论】:

        猜你喜欢
        • 2020-06-29
        • 1970-01-01
        • 1970-01-01
        • 2019-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-29
        • 1970-01-01
        相关资源
        最近更新 更多