Postgresql JSONB查询聚合



试图用以下数据计算JsonB列的聚合结果

part          | data
-----------------------------------
PART1         |[{"type":"box","reference": "box1"},{"type": "dispatch","reference": 
"d1"},{"type": "dispatch","reference": "d2"}]

需要编写一个查询,该查询只能提取type=dispatch的聚合结果查询的预期结果是

part          | data
-----------------------------------
PART1         |d1,d2

找到了这些执行的一些示例,但它们都不适用于带有数组的JSONB,其中大多数都能够处理对象,即使不需要过滤器。

您可以使用JSON路径查询将这些值作为JSON数组返回:

select part, 
jsonb_path_query_array(data, '$[*] ? (@.type == "dispatch").reference')
from the_table

不过,将其转换为逗号分隔的列表会有点麻烦。

最终找到了以下查询问题的解决方案

select part,(select string_agg(t->>'reference',',') from jsonb_array_elements(data::jsonb) as x(t) where t->>'type' ='dispatch') as output

以下帖子有助于达成解决方案

最新更新