2012-10-29 366 views
2

可能重複:
Transposing an sql result so that one column goes onto multiple columns如何轉置PostgreSQL中的列和行(即,如何切換行和列)?

我想要做一個排序行/列交換的在我的PSQL數據庫。下面是我的示例數據庫:

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 

我想那個表格轉換爲下面的例子:

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

這可能在PostgreSQL的?

+0

如果您搜索術語[tag:piv],您會發現很多結果,不一定與postgres相關。 OT。請注意,Oracle和SQL Server實際上實現了'PIVOT'子句,但不是Postgres –

+3

查看tablefunc模塊中的交叉表函數:http://www.postgresql.org/docs/current/static/tablefunc.html –

+0

請參閱: https://github.com/jumpstarter-io/colpivot獲取動態解決方案。 –

回答

7

您可以通過聚合函數和CASE聲明容易做到這一點:

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 

SQL Fiddle with Demo

0

這就是所謂的「支點」,並有Postgres裏沒有特殊的語法來支持它 - 您必須使用SQL對其進行編碼,例如:

select 
    year, 
    us.price as us, 
    uk.price as uk 
from mytable us 
left join mytable uk on us.year = uk.year 
+1

做到了100列,你註定了......見http://en.wikipedia.org/wiki/Relational_algebra#Natural_join_.28.E2.8B.88.29 – boecko