【问题标题】:How create a column containing columns as values in redshift?如何在redshift中创建包含列作为值的列?
【发布时间】:2020-10-13 16:08:11
【问题描述】:

我有如下数据:

id                  start_date   end_date   col1   col2   col3   col4   col5
issue_2017-09       2017-09-18  2017-09-30  true   true   true   true   false

我想将数据转换成以下格式:

id                 start_date    end_date     new_col
issue_2017-09      2017-09-18    2017-09-30   {'col1', 'col2', 'col3', 'col4'}

new_col 是由 [col1, col2, col3, col4, col5] 为真的列创建的。 另外我正在使用红移。

【问题讨论】:

    标签: amazon-web-services amazon-redshift


    【解决方案1】:

    我能够使用以下查询解决此问题:

    select id, start_date , end_date, listagg(col_name, ', ') as new_col
    from (
       select id, start_date, end_date, col1 as val, 'col1' as col_name
       from table
       union all
       select id, start_date, end_date, col2 as val, 'col2' as col_name
       from table
       union all
       select id, start_date, end_date, col3 as val, 'col3' as col_name
       from table
       union all
       select id, start_date, end_date, col4 as val, 'col4' as col_name
       from table
       union all
      select id, start_date, end_date, col5 as val, 'col5' as col_name
       from table
    ) t
    where val is True
    group by id, start_date, end_date  
    

    【讨论】:

      【解决方案2】:

      这是另一种方法,

      select
        id, start_date, end_date, 
        '{' + 
        case when col1 then '''col1''' else '' end +
        case when col2 then case when col1 then ', ''col2''' else '''col2''' end else '' end +
        case when col3 then case when (col1 or col2) then ', ''col3''' else '''col3''' end else '' end +
        case when col4 then case when (col1 or col2 or col3) then ', ''col4''' else '''col4''' end else '' end +
        case when col5 then case when (col1 or col2 or col3 or col4) then ', ''col5''' else '''col5''' end else '' end +
        '}' as new_col 
       from table01;
      

      【讨论】:

        猜你喜欢
        • 2017-10-01
        • 2017-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-27
        相关资源
        最近更新 更多