【问题标题】:presto - concat columns namespresto - 连接列名称
【发布时间】:2021-01-02 00:24:24
【问题描述】:

是否可以将列名连接到数组中? 例如,我的表是:

key|name_changed|address_changed|number_changed
-----------------------------------------------
1  |true        |true           |false

我想得到:

key|changes
---------------------------------
1  |[name, address]

【问题讨论】:

    标签: sql presto


    【解决方案1】:

    如果你想要一个数组:

    select key,
           ((case when name_changed then array['name'] end) ||
            (case when address_changed then array['address'] end) ||
            (case when number_changed then array['number'] end)
           ) as changes
    

    Here 是一个使用 Postgres 的 dbfiddle,在处理数组方面应该与 Presto 非常相似。

    【讨论】:

      【解决方案2】:

      假设您想要一个数组作为输出,您可以通过几种不同的方式来解决这个问题。

      一种方法是创建一个数组,其中每列的标签作为元素,如果元素为 false,则为 NULL。这是通过表达式if(name_changed, 'name') 实现的,它是CASE WHEN condition THEN if_true END 的简写。请注意,如果条件为假,它将返回 NULL。要从结果数组中删除空值,请将 filter 函数与排除空值的 lambda expression 一起使用:e -> e is not null

      WITH data(key, name_changed, address_changed, number_changed)
      AS (values (1, true, true, false))
      SELECT 
          key,
          filter(
              array[if(name_changed, 'name'), if(address_changed, 'address'), if(number_changed, 'number')], 
              e -> e is not null) AS changes
      FROM data
      

      避免使用filter 的另一个选项是为每个标签创建一个数组,然后将它们连接在一起。它类似于上面的其他答案,但请注意,在 Presto(和标准 SQL)中,如果 || 运算符的任何参数是 NULL,则结果是 NULL。为了解决这个问题,如果条件为假,则从每个 if 表达式中返回一个空数组:

      WITH data(key, name_changed, address_changed, number_changed)
      AS (values (1, true, true, false))
      SELECT 
          key,
          if(name_changed, array['name'], array[]) || 
          if(address_changed, array['address'], array[]) || 
          if(number_changed, array['number'], array[]) AS changes
      FROM data
      

      【讨论】:

        【解决方案3】:
        select  key
                    , concat(   case when name_changed = true then 'name' end, ', ',
                                case when address_changed = true then 'address' end, ', ', case when address_changed = true then 'address' end) as changes
        

        【讨论】:

        • 虽然这可能会回答 OP 的问题,但请提供答案的解释。
        猜你喜欢
        • 1970-01-01
        • 2019-04-22
        • 2019-06-21
        • 1970-01-01
        • 2020-08-31
        • 2021-03-22
        • 2018-09-10
        • 2021-04-12
        • 1970-01-01
        相关资源
        最近更新 更多