首页 > 解决方案 > 将 Postgres JSONB 数组转换为单列中的逗号分隔列表

问题描述

我在表中有 JSONB 转换列,我想将其表示为单列中的逗号分隔列表。我已经尝试了一百万种不同的方法,但都做不到。我在 Postgres 文档中找不到任何解决这种特殊情况的内容,因此希望得到一些帮助!

有问题的表看起来有点像这样:

date       | order_id | sales_reps
2019-12-01 | 1234     | [{"id": 100, "user": "Jane Doe"}, {"id": 101, "user": "John Doe"}]

我想将其渲染为:

date       | order_id | sales_reps
2019-12-01 | 1234     | Jane Doe, John Doe

我能够比较接近:

select
    date,
    order_id, 
    (select jsonb_agg(t -> 'user') from jsonb_array_elements(sales_reps::jsonb) as x(t)) as sales_reps
from table
date       | order_id | sales_reps
2019-12-01 | 1234     | ["Jane Doe", "John Doe"]

但是对于我的生活,我似乎无法获得我想要的输出 - 尝试了大量的聚合器和 jsonb 函数无济于事。

标签: jsonpostgresqlaggregate-functionsjsonb

解决方案


使用->>运算符获取 json 值作为文本和string_agg()聚合:

select
    date,
    order_id,
    (
        select string_agg(t->>'user', ',') 
        from jsonb_array_elements(sales_reps::jsonb) as x(t)
    ) as sales_reps
from my_table

Db<>小提琴。


推荐阅读