admin

postgres聚合函数调用可能未嵌套

sql

我有一个查询:

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

但是我不能在postgres中执行此操作,因为它使用嵌套的聚合。还有另一种不用嵌套聚合写此方法的方法吗?


阅读 297

收藏
2021-06-07

共1个答案

admin

我假设您需要先计算某些项目组的内部公式,然后再对结果求和。我将product列用作对列进行分组的任意选择。我也改名Countdcount

SQLFiddle

样本数据:

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);

询问:

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

关键是您不能嵌套聚合函数。如果需要聚合聚合,则需要使用子查询。

2021-06-07