Postgres GROUP BY on jsonb internal field

I am using Postgresql 9.4 and have a table testwith id::intand content::jsonbas follows:

 id |     content
----+-----------------
  1 | {"a": {"b": 1}}
  2 | {"a": {"b": 1}}
  3 | {"a": {"b": 2}}
  4 | {"a": {"c": 1}}

How am I GROUP BYin the internal field of a column contentand return each group as an array? In particular, the results I'm looking for are as follows:

             content
---------------------------------
[{"a": {"b": 1}},{"a": {"b": 1}}]
[{"a": {"b": 2}}]
(2 rows)

Attempt:

SELECT json_agg(content) as content FROM test GROUP BY content ->> '{a,b}';

Productivity:

                               content
----------------------------------------------------------------------
[{"a": {"b": 1}}, {"a": {"b": 1}}, {"a": {"b": 2}}, {"a": {"c": 1}}]
(1 row)
+4
source share
1 answer

You should use the operator #>>instead ->>when the right operand is the json path. Try the following:

SELECT json_agg(content) as content FROM test GROUP BY content #>> '{a,b}';

Productivity:

              content
------------------------------------
 [{"a": {"c": 1}}]
 [{"a": {"b": 2}}]
 [{"a": {"b": 1}}, {"a": {"b": 1}}]
(3 rows)
+1
source

Source: https://habr.com/ru/post/1653231/


All Articles