从 JSON 对象数组中提取 JSON 数字数组

Vak*_*lov 6 postgresql array json

我有一个包含类似于此对象的 json 数组的表:

id    |   record
____________________
name1 | [{"a":0, "b":x}, {"a":1, "b":y}, {"a":2, "b":z}, ...]
Run Code Online (Sandbox Code Playgroud)

我想得到一个包含仅包含“a”值的 json 数组的表:

id    |   record
____________________
name1 | [0, 1, 2, ...]
Run Code Online (Sandbox Code Playgroud)

我使用的是 PostgreSQL 11,所以最新的功能是可以接受的。

a_h*_*ame 8

您需要首先取消嵌套数组元素,然后聚合回每个值:

select id, 
       (select jsonb_agg(t -> 'a') from jsonb_array_elements(record) as x(t)) as record
from the_table;
Run Code Online (Sandbox Code Playgroud)

在线示例:https : //rextester.com/ZONHTW97204