This is a pivot query problem. I couldn't find any good examples for Postgres (using Google; I assume you're using Postgres from the comments in the code). However, I did find some Oracle examples that will probably get you started:
- http://asktom.oracle.com/pls/ask/f?p=4950:8:285894::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:766825833740,%7Bpivot%7D%20and%20%7Bquery%7D
- one from ArsDigita
Where the above examples make use of DECODE, you can use a CASE construct instead. This page describes how to convert DECODE into CASE.
Hope this helps.