在 (Amazon Redshift) 中将 varchar 值的行转为列
Pivot row to columns for varchar values in (Amazon Redshift)
下面的table是一个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
我想将上面的 table 转换为:
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
下面的代码returns语法错误:
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;
下面的table是一个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
我想将上面的 table 转换为:
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
下面的代码returns语法错误:
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;