【问题标题】:Postgres: How to copy elements from text array column into a json column?Postgres:如何将文本数组列中的元素复制到 json 列中?
【发布时间】:2018-10-29 15:00:26
【问题描述】:

我有一个文本数组列,现在我想创建一个新的 JSON 列。在 JSON 列中,我想从文本数组和当前时间戳创建键值对。

示例:

文本数组{"aa", "bb", "cc"} -> JSON {"aa":"12:00", "bb":"12:00", "cc":"12:00"}

如何以这种方式更新整个表中的所有行?

【问题讨论】:

    标签: sql json postgresql


    【解决方案1】:

    假设当前列名为data,新列名为new_data,您可以执行以下操作:

    update the_table
      set new_data = x.new_data
    from (
      select id, jsonb_object_agg(t.k, to_char(now(), 'hh24:mi')) as new_data
      from the_table, unnest(data) as t(k)
      group by id
    ) x
    where x.id = foo.id;
    

    在线示例:https://rextester.com/SMBH72985

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      • 1970-01-01
      • 2017-04-25
      • 2019-12-20
      • 2021-06-30
      相关资源
      最近更新 更多