【问题标题】:How to transpose columns and rows in PostgreSQL (i.e., how do I switch rows and columns)? [duplicate]如何在 PostgreSQL 中转置列和行(即如何切换行和列)? [复制]
【发布时间】:2012-10-29 18:59:14
【问题描述】:

可能重复:
Transposing an sql result so that one column goes onto multiple columns

我想在我的 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 中可行吗?

【问题讨论】:

标签: sql postgresql pivot


【解决方案1】:

您可以使用聚合函数和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

【讨论】:

    【解决方案2】:

    这被称为“pivot”,在 postgres 中没有特殊的语法来支持它 - 您必须使用 SQL 对其进行编码,例如:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多