2010-09-13 94 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) 

...等。對於每一個總計,但我不認爲這是一個好方法。只是似乎無法找出更好的東西。

回答