【问题标题】:Nested aggregate and subquery in postgresql/SQL with grouping带有分组的postgresql/SQL中的嵌套聚合和子查询
【发布时间】:2010-09-13 23:36:45
【问题描述】:

我需要在 Postgresql 8.3 中通过嵌套子查询获得的一堆不同聚合上执行相同的分组。

如果我这样做:

select f10 as report_id,
       (SELECT AVG(age)
          FROM (select f10 as report_id,  
                       f62 as age 
                  from reports 
                 where f55 in ('1')) 
                   and f62 in ('1', '2', '3', '4', '5'))) foo
      group by report_id) as agg1,
       (SELECT AVG(age)
          FROM (select f10 as report_id, 
                       f62 as age 
                  from reports 
                 where f55 in ('2')) 
                   and f62 in ('1', '2', '3', '4', '5'))) foo
      group by report_id) as agg2,
    from reports
group by report_id;

这几乎是我想要的,但 group by 没有做任何事情 - 所有聚合都是相同的,它是所有 report_ids 的聚合。我希望每个 report_id 有一个单独的聚合。

如果我尝试在聚合中进行分组,那么我不能返回超过 2 个字段或行,因此它不起作用。

有人建议我这样做

sum(case  
      when f55 in ('1') then f62 
      else 0 
    end) / sum(case 
                 when f55 in ('1') then 1 
                 else 0 
               end) 

...等等。对于每个聚合,但我认为这不是一个好方法。只是似乎想不出更好的办法。

【问题讨论】:

    标签: sql postgresql aggregate-functions


    【解决方案1】:

    【讨论】:

    • 我无法访问该网页
    • 我正在投票赞成这个答案,因为这个问题已经过时了,而且 8.3 可能会在不到一年的时间内得到支持。虽然当时可能还不够,但两年后最好的答案是“升级”。
    猜你喜欢
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多