我正在使用Postgresql 9.4,并有test
和id::int
的表content::jsonb
,如下所示:
id | content
----+-----------------
1 | {"a": {"b": 1}}
2 | {"a": {"b": 1}}
3 | {"a": {"b": 2}}
4 | {"a": {"c": 1}}
如何在GROUP BY
列的内部字段上content
并将每个组作为数组返回?具体来说,我要找的结果是:
content
---------------------------------
[{"a": {"b": 1}},{"a": {"b": 1}}]
[{"a": {"b": 2}}]
(2 rows)
尝试:
SELECT json_agg(content) as content FROM test GROUP BY content ->> '{a,b}';
收率:
content
----------------------------------------------------------------------
[{"a": {"b": 1}}, {"a": {"b": 1}}, {"a": {"b": 2}}, {"a": {"c": 1}}]
(1 row)
答案 0 :(得分:6)
当右操作数是json路径时,您必须使用#>>
运算符而不是->>
。试试这个:
SELECT json_agg(content) as content FROM test GROUP BY content #>> '{a,b}';
收率:
content
------------------------------------
[{"a": {"c": 1}}]
[{"a": {"b": 2}}]
[{"a": {"b": 1}}, {"a": {"b": 1}}]
(3 rows)