聚合函数调用不能嵌套postgresql

时间:2017-03-30 11:47:47

标签: sql postgresql

我从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 ;

谢谢!

3 个答案:

答案 0 :(得分:1)

如果您想统计在一次感受中看过两个页面的用户,那么这就是查询:

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;

这是我能想象到的最明智的解释。

答案 1 :(得分:0)

您可以使用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 :(得分:0)

我不完全理解您在此示例中要做什么,但是我想展示一个示例,说明如何在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;

我希望这很清楚!