首页 > 解决方案 > 如何在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'
)

我使用的表 braze_currents.campaigns_conversion_partitioned 如下所示

img2 链接

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

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

标签: sqlpresto

解决方案


我认为您正在寻找有条件的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

推荐阅读