2010-09-13 60 views
0

我需要做一组不同的聚合,我在Postgresql 8.3中嵌套的子查询得到相同的组。Postgresql中的嵌套聚合和子查询/ SQL与分组

如果我这样做:

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; 

这几乎是我想要的,但该组由没有做任何东西 - 所有的聚集都是一样的,它是在所有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) 

...等。对于每一个总计,但我不认为这是一个好方法。只是似乎无法找出更好的东西。

回答