[英]Convert Postgres JSONB array to comma separated list in a single column
我在表中有 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 函数无济于事。
使用->>
运算符将 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.