簡體   English   中英

查詢以列格式獲取多行數據 - postgresql

[英]query to fetch multiple row data in Columns format - postgresql

我有這樣的表結構:表 - 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 的“null”,發生的情況是,如果所有三個角色的數據都存在,則整行都出現,或者如果任何角色丟失,整行丟失。

有人可以建議這種方法嗎?

-- 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM