我有这样的表结构:table-contact_details
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,如果所有三个角色的数据都存在,则会出现整行,或者如果任何角色丢失,则会丢失整行。
谁能建议一下这种方法吗?
--Postgres版本-12
您可以尝试使用此(条件聚合(
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