簡體   English   中英

Pivot (Amazon Redshift) 中 varchar 值的行到列

[英]Pivot row to columns for varchar values in (Amazon Redshift)

下表包含一種格式,其中一個 id 包含許多行。

select id,name,value 
from table

"id","name","value"
"a1",newsletters,true
"a1",gdpr_marketing_opt_in,true
"a1",new_widget,true
"b2",newsletters,true
"b2",newsletters_2016,true
"c3",app_shell,true
"c3",sms_reminders,true
"c3",new_widget,true
"c3",online_booking,true
"c3",merchant_shiftplan,true

我想把上面的表pivot改成:

id newsletters  gdpr_marketing_opt_in new_widget  app_shell     sms_reminders   online_booking
a1    true           true              true        null            null              null
b2    true           null              null        null            null              null
c3    null           null              true        true            true              true

下面的代碼返回語法錯誤:

SELECT *
from schema.table t
PIVOT
(
    max(value)
    FOR UG_LABEL IN ([newsletters], [gdpr_marketing_opt_in], [new_widget], [app_shell])
) p

在 Redshift 中,您可以像這樣使用條件聚合:

select id, 
       max(case when name = 'newsletters' then value end) as newsletters,
       max(case when name = 'gdpr_marketing_opt_in' then value end) as gdpr_marketing_opt_in,
       max(case when name = 'new_widget' then value end) as new_widget,
       max(case when name = 'app_shell' then value end) as app_shell,
       max(case when name = 'sms_reminders' then value end) as sms_reminders,
       max(case when name = 'online_booking' then value end) as online_booking
from the_table
group by id;

暫無
暫無

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

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