使用聚合之前,您应该UNNEST数组:
with my_table(id, data) as (
values
(1, '["x", "y", "z"]'::jsonb),
(2, '["a", "b", "x"]')
)
select jsonb_agg(distinct value)
from my_table, jsonb_array_elements_text(data);
jsonb_agg
---------------------------
["a", "b", "x", "y", "z"]
(1 row)
您可以将结果:
with my_table(id, data) as (
values
(1, '["x", "y", "z"]'::jsonb),
(1, '["a", "b", "x"]'),
(2, '["1", "2", "3"]'),
(2, '["2", "3", "4"]')
)
select id, jsonb_agg(distinct value)
from my_table, jsonb_array_elements_text(data)
group by id;
id | jsonb_agg
----+---------------------------
1 | ["a", "b", "x", "y", "z"]
2 | ["1", "2", "3", "4"]
(2 rows)
谢谢!你知道在窗口函数中是否有任何方法使用这种方法? (就像组合所有具有相同'id'的行)。 –
您不需要窗口函数,请参阅已更新的答案。 – klin