【问题标题】:Pivoting a table in PostgreSQL在 PostgreSQL 中透视表
【发布时间】:2021-04-01 21:29:44
【问题描述】:

数据库新手,我有下表,我需要将列值转换为行,有人可以帮忙。

以下是我已有的源数据:

id              custom_key  custom_value
648079          WrapUpName  Default Wrap-up Code
648079          agentEmail  abc@gmail.com
648079          Location    Hyderabad
648079          Supervisor  Vinay
648079          Publication xyz
648122          WrapUpName  Default Wrap-up
648122          agentEmail  efg@gmail.com
648122          Location    Mumbai
648122          Supervisor  Pranay
648122          Publication mnp

我需要使用 PostgreSQL 查询将上述值转换​​为以下格式。

id              WrapUpName              agentEmail      Location    Supervisor  Publication
648079          Default Wrap-up Code    abc@gmail.com   Hyderabad   Vinay       xyz
648122          Default Wrap-up Code    efg@gmail.com   Mumbai      Pranay      mnp

【问题讨论】:

标签: sql postgresql pivot aggregate-functions


【解决方案1】:

只使用条件聚合:

select id,
    max(custom_value) filter(where custom_key = 'WrapUpName') as wrap_up_name,
    max(custom_value) filter(where custom_key = 'agentEmail') as agent_email
    ...
from mytable
group by id

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多