2

Possible Duplicate:
Transposing an sql result so that one column goes onto multiple columns

I'd like to do a sort of row/column swapping in my PSQL database. Here's my example database:

id  place   price   year
1   U.S.    80  2000
2   U.S.    60  2001
3   U.S.    40  2002    
4   U.K.    600 2000
5   U.K.    500 2001
6   U.K.    350 2002

I would like to transform that table into the following example:

year    U.S.    U.K.
2000    80  600
2001    60  500
2002    40  350

Is this possible in PostgreSQL?

Community
  • 1
  • 1
user1626730
  • 3,223
  • 5
  • 18
  • 24

2 Answers2

8

You can do this easily with an aggregate function and a CASE statement:

select year,
  sum(case when place = 'U.S.' then price else 0 end) "U.S.",
  sum(case when place = 'U.K.' then price else 0 end) "U.K."
from yourtable
group by year

See SQL Fiddle with Demo

Taryn
  • 234,956
  • 54
  • 359
  • 399
0

This is called a "pivot", and there's no special syntax in postgres to support it - you have to code it using SQL, for example:

select
    year,
    us.price as us,
    uk.price as uk
from mytable us
left join mytable uk on us.year = uk.year
Bohemian
  • 389,931
  • 88
  • 552
  • 692
  • 1
    do that with 100 columns and you're doomed … see http://en.wikipedia.org/wiki/Relational_algebra#Natural_join_.28.E2.8B.88.29 – boecko Nov 06 '12 at 14:37