7

I have a query:

    select sum(
        sum((Impressions / Count) * Volume) / sum(Volume)
    ) as frequency 
    from datatable;

however I cannot execute this in postgres because it uses nested aggregations. Is there another way to write this without using nested aggregations?

4
  • What do you think it means? Can you give some example data/results? Commented Jun 5, 2014 at 16:16
  • What do you think the outer sum() does? It seems that the term sum((Impressions / Count) * Volume) / sum(Volume) should be only one value so I don't know what the outer sum() could be doing. Commented Jun 5, 2014 at 16:42
  • Please define "this". What you display so far does not make sense. Start with the table definition (\d tbl in psql) and your version of Postgres. Add an explanation of what you are trying to achieve. Commented Jun 5, 2014 at 16:57
  • Possible duplicate of Nesting Aggregate Functions - SQL Commented Jul 15, 2017 at 6:25

1 Answer 1

14

If you need to nest aggregation functions, you will need to use some form of subquery. I am using product column as an arbitrary choice for grouping column. I also renamed Count to dcount.

SQLFiddle

Sample data:

create table sample (
  product varchar,
  dcount int,
  impressions int,
  volume int
);

insert into sample values ('a', 100, 10, 50);
insert into sample values ('a', 100, 20, 40);
insert into sample values ('b', 100, 30, 30);
insert into sample values ('b', 100, 40, 30);
insert into sample values ('c', 100, 50, 10);
insert into sample values ('c', 100, 60, 100);

Query:

select
  sum(frequency) as frequency
from 
  (
  select
    product,
    sum((impressions / dcount::numeric) * volume) / sum(volume) as frequency
  from 
    sample
  group by
    product
  ) x;

The point is that you cannot nest aggregate functions. If you need to aggregate aggregates then you need to use subquery.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.