将 Postgres JSONB 数组转换为单列中的逗号分隔列表
Convert Postgres JSONB array to comma separated list in a single column
我在 table 中有 JSONB 转换列,我想将其表示为单个列中的逗号分隔列表。我已经尝试了一百万种不同的方法,但效果不佳。我在 Postgres 文档中找不到解决这种特殊情况的任何内容,因此希望得到一些帮助!
有问题的table看起来有点像这样:
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 函数都无济于事。
使用 ->>
运算符获取 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
我在 table 中有 JSONB 转换列,我想将其表示为单个列中的逗号分隔列表。我已经尝试了一百万种不同的方法,但效果不佳。我在 Postgres 文档中找不到解决这种特殊情况的任何内容,因此希望得到一些帮助!
有问题的table看起来有点像这样:
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 函数都无济于事。
使用 ->>
运算符获取 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