Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I need to do the same group by on a bunch of different aggregates that I'm getting with nested subqueries in Postgresql 8.3.

If I do this:

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;

it is almost what I want but the group by doesn't do anything- all the aggregates are the same, it is an aggregate across all report_ids. I want a separate aggregate per report_id.

If I try to do the grouping within the aggregates then I can't return more than 2 fields or rows and so it doesn't work.

It has been suggested to me to do

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

...etc. for each of the aggregates but I don't think this is a good way to go. Just can't seem to figure out anything better.

share|improve this question

1 Answer 1

You might want to look into window functions:

http://wiki.postgresql.org/wiki/What's_new_in_PostgreSQL_9.0#New_frame_options_for_window_functions

share|improve this answer
    
the web page is not available for me –  Mohsen Oct 5 '11 at 10:59
    
I am voting up this answer since the question is old and 8.3 will probably be supported less than another year. While it might not be sufficient at the time it was given, the best answer two years later is "upgrade." –  Chris Travers Oct 3 '12 at 1:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.