繁体   English   中英

在 PostgreSQL 中旋转表

[英]Pivoting a table in PostgreSQL

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

以下是我已经拥有的源数据:

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

只需使用条件聚合:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM