我正在使用Postgresql 9.4,并具有一个表test,带有id::int和content::jsonb,如下所示:
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列的内部字段上将每个组作为数组返回?具体来说,我正在寻找的结果是:
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)
您必须使用#>>运算符,而不是->>在正确的操作数是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)