【问题标题】:postgres unnest json array given criteriapostgres unnest json数组给定条件
【发布时间】:2021-02-02 15:41:38
【问题描述】:

我一般是 json 数组的新手,但特别是 postgresql 并正在寻找一些指导 -

我有一张这样的桌子-

indicator    array
1           [["abc","snow"],"abc","rain"]]
2           [["abc","snow"],["efg","snow"],["abc","rain"],["efg","rain"]]

所以,我想根据指标提取字母。如果为 1 则为“abc”,如果为 2 则为“abc”和“efg”。像这样-

indicator     array                                                          output
1           [["abc","snow"],"abc","rain"]]                                    abc
2           [["abc","snow"],["efg","snow"],["abc","rain"],["efg","rain"]]     abc,efg

感谢您的指导

【问题讨论】:

    标签: arrays json postgresql


    【解决方案1】:

    step-by-step demo:db<>fiddle

    SELECT
        indicator,
        data,
        string_agg(DISTINCT elem ->> 0, ',')    -- 3
    FROM mytable,
        jsonb_array_elements(data) as elem      -- 1
    GROUP BY indicator, data                    -- 2
    
    1. 将所有数组元素提取到自己的记录中
    2. 使用以下聚合重新聚合它们:
    3. a) 以文本形式获取第一个数组元素 (-&gt;&gt; 0) b) 使用 DISTINCT 删除重复项 c) 使用 string_agg() 聚合为字符串列表

    【讨论】:

    • 感谢您的快速回复!在尝试时,我遇到了不匹配的输入错误 - mismatched input '&gt;'. Expecting: &lt;expression&gt;
    • 正如您在小提琴中看到的那样,这在那里有效。请尝试在小提琴中构建您的问题,以便我可以查看它。
    • 我确实看到工作和问题似乎构造正确,但不确定为什么它不能为我翻译。只是这样做我得到一个不匹配的输入错误SELECT * FROM mytable, jsonb_array_elements(data)
    • 这是array(row(id varchar, weather varchar))类型的输出
    • 您需要将天气转换为 jsonb 类型:weather::jsonb 我正在使用 data... 我猜...
    【解决方案2】:

    cmets 中的答案有助于理解小提琴及其在其中的工作原理,谢谢!但是,它不适用于我的用例,所以我把它放在一起,最终为我解决了这个问题。可能会更迂回一些,但效果很好。

    用于将 JSON 数组列拆分为 2:

    select indicator,data 
    split_part(replace(replace(replace(json_format(cast(array_agg(DISTINCT id as JSON)), '[', ''), ']', ''), '"', ''),',',1)  as id_1,
    split_part(replace(replace(replace(json_format(cast(array_agg(DISTINCT id) as JSON)), '[', ''), ']', ''), '"', ''),',',2)  as id_2
    from mytable
    CROSS JOIN UNNEST(data) as (id, weather)
    

    对于单列:

    select indicator,data 
    replace(replace(replace(json_format(cast(array_agg(DISTINCT id) as JSON)), '[', ''), ']', ''), '"', '')  as id_new
    from mytable
    CROSS JOIN UNNEST(data) as (id, weather)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 2021-06-18
      • 2021-12-06
      • 2020-08-23
      • 2022-10-13
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      相关资源
      最近更新 更多