获取列格式的多行数据的查询-postgresql

获取列格式的多行数据的查询-postgresql,sql,postgresql,pivot,left-join,self-join,Sql,Postgresql,Pivot,Left Join,Self Join,我有这样的表结构:表-联系人详细信息 role email userId Primary Contact a1@b.com 1 Secondary Contact b1@b.com 1 End User c1@b.com 1 Primary Contact a2@b.com 2 Secondary Contact b2@b.com 2 结果数据

我有这样的表结构:表-联系人详细信息

role                email        userId
Primary Contact    a1@b.com        1
Secondary Contact  b1@b.com        1
End User           c1@b.com        1

Primary Contact    a2@b.com        2
Secondary Contact  b2@b.com        2
结果数据应为:

Primary Contact       Secondary Contact    End User      UserId
a1@b.com                  b1@b.com          c1@b.com       1
a2@b.com                  b2@b.com          null           2
我无法将userId-2的最终用户检索为“null”,如果所有三个角色都存在数据,则会出现整行,或者任何角色缺少整行

有谁能建议一下方法吗

--Postgres版本-12

您可以尝试使用此(条件聚合)


杰出的感谢你的知识。它完成了我的工作。非常感谢。很高兴帮助@AbhishekSingh
select
  max(case when role = 'Primary Contact' then email else null end) as PrimaryContact,
  max(case when role = 'Secondary Contact' then email else null end) as SecondaryContact,
  max(case when role = 'End User' then email else null end) as EndUser,
  userId    
from contact_details
group by userId