Postgres GROUP BY在jsonb内场

时间:2016-09-01 01:30:02

标签: sql json postgresql postgresql-9.4 jsonb

我正在使用Postgresql 9.4,并有testid::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)

1 个答案:

答案 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)