Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aggregate function calls cannot be nested postgresql

Tags:

sql

postgresql

I get "aggregate function calls cannot be nested" error from PostgreSQL. I tried different bunch of things but could not solve.

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 ;

Thanks!

like image 673
uhuuyouneverknow Avatar asked Jun 22 '26 05:06

uhuuyouneverknow


2 Answers

You can just use subselect to get nested aggregate functions, like this:

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 ;
like image 187
Łukasz Kamiński Avatar answered Jun 24 '26 01:06

Łukasz Kamiński


I don't completely understand what you are trying to do in this example, however I would like to show an example of how I used multiple aggregating functions in PostgresQL.

Suppose my goal is to find maximum of 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;

I hope this is clear!

like image 28
Akshaya Natarajan Avatar answered Jun 24 '26 00:06

Akshaya Natarajan