Postgresql JSONB 查询聚合
Postgresql JSONB Query Aggregation
正在尝试计算具有以下数据的 JsonB 列的聚合结果
part | data
-----------------------------------
PART1 |[{"type":"box","reference": "box1"},{"type": "dispatch","reference":
"d1"},{"type": "dispatch","reference": "d2"}]
需要编写一个查询,只提取 type = dispatch 的聚合结果
查询的预期结果是
part | data
-----------------------------------
PART1 |d1,d2
为这些执行找到了一些示例,但其中 none 适用于带有数组的 JSONB,其中大多数都能够处理对象,甚至在不需要过滤器时也是如此。
您可以使用 JSON 路径查询 return 这些值作为 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
有助于找到解决方案
正在尝试计算具有以下数据的 JsonB 列的聚合结果
part | data
-----------------------------------
PART1 |[{"type":"box","reference": "box1"},{"type": "dispatch","reference":
"d1"},{"type": "dispatch","reference": "d2"}]
需要编写一个查询,只提取 type = dispatch 的聚合结果 查询的预期结果是
part | data
-----------------------------------
PART1 |d1,d2
为这些执行找到了一些示例,但其中 none 适用于带有数组的 JSONB,其中大多数都能够处理对象,甚至在不需要过滤器时也是如此。
您可以使用 JSON 路径查询 return 这些值作为 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