如何在 presto sql 中将行的不同值转换为列

how to make different values of rows into columns in presto sql

我想知道是否可以在 presto 中将行的每个不同值放入不同的列中

例如,我想要得到如下形式的结果

message_varation_id / first_cv / second_cv / third_cv / fourth_cv 

然而我最终得到的是如下图

其中充满了我不想要的空白值,我得到了四行(对于不同的值,我希望行在 message_variation_id 之前是唯一的)

例如,在这种情况下我想要得到的输出是

message_variation_id | first_cv | second_cv | third_cv | fourth_cv
-------------------------------------------------------------------
9617b279~            | {custom~}| {window=~}|{custom~} | {custom ~} 

我使用了如下代码

select distinct message_variation_id, first_cv, second_cv, third_cv, fourth_cv 
from (
select distinct message_variation_id
    , if(bcc.conversion_behavior_index = 0, bcc.conversion_behavior) first_cv
    , if(bcc.conversion_behavior_index = 1, bcc.conversion_behavior) second_cv
    , if(bcc.conversion_behavior_index = 2, bcc.conversion_behavior) third_cv
    , if(bcc.conversion_behavior_index = 3, bcc.conversion_behavior) fourth_cv
from braze_currents.campaigns_conversion_partitioned bcc
where message_variation_id = '9617b279-f5bd-452d-abca-3263cf7e4651'
)

和我用的table,braze_currents.campaigns_conversion_partitioned如下所示

select message_variation_id, conversion_behavior_index, conversion_behavior
from braze_currents.campaigns_conversion_partitioned
limit 10

我认为这是因为空值,但有时 third_cv 或 fourth_cv 没有值,所以我做了上面的查询。我正在考虑使用连接查询,但我认为可能有一种有效的方法。任何建议都会很棒,谢谢! :)

我认为你正在寻找一个有条件的max()(你的图片很难看懂):

select message_variation_id, 
       max(case when bcc.conversion_behavior_index = 0 then  bcc.conversion_behavior end) as first_cv,
       max(case when bcc.conversion_behavior_index = 1 then bcc.conversion_behavior end) second_cv,
       max(case when bcc.conversion_behavior_index = 2 then bcc.conversion_behavior end) as third_cv,
       max(case when bcc.conversion_behavior_index = 3 then bcc.conversion_behavior end) as fourth_cv
from braze_currents.campaigns_conversion_partitioned bcc
where message_variation_id = '9617b279-f5bd-452d-abca-3263cf7e4651'
group by message_variation_id

我认为下面的 sql 应该可行。

select message_variation_id, 
       GROUP_CONCAT(DISTINCT first_cv SEPARATOR '') as first_cv,
       GROUP_CONCAT(DISTINCT second_cv SEPARATOR '') as second_cv,
       GROUP_CONCAT(DISTINCT third_cv SEPARATOR '') as third_cv,
       GROUP_CONCAT(DISTINCT fourth_cv SEPARATOR '') as fourth_cv
from braze_currents.campaigns_conversion_partitioned
group by message_variation_id;