json - 将 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 函数无济于事。
解决方案
使用->>
运算符获取 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
推荐阅读
- flutter - 如何在 Flutter 中创建录音应用?
- c++ - 直接在类构造上初始化一个 shared_ptr
- d3.js - D3 日历热图。如何在热图的矩形中显示数字或任何内容
- sql - SQL计算两次之间的时间差并显示小时
- python - plotly dash中的外部css
- php - 如何获取当前帖子的作者 ID(WordPress)
- javascript - getSourceData(), afterchange Handsontable js vue
- react-native - 如何在用户滑动时从 PanGestureHandler 滑动移动获取当前 Y 值
- xml - 使用 Biopython 为 SARS 病毒在 Python 中运行 BLAST。我的输出根本没有出现!有人检查我的代码吗?
- python - 为什么在 zip() 上调用 list() 会清空内容?如何在不更改内容的情况下打印 zip 对象?