json aggregation question

From: Chris Withers <chris(at)withers(dot)org>
To: pgsql-general(at)postgresql(dot)org
Subject: json aggregation question
Date: 2017-02-28 16:21:12
Message-ID: fd1a6fb0-cec9-49b6-9c98-35774d9a86e7@withers.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi All,

Given the following table:

|#createtablething (id serial,tags jsonb);#\d thing
Table"public.thing"Column|Type |Modifiers
--------+---------+----------------------------------------------------id
|integer |notnulldefaultnextval('thing_id_seq'::regclass)tags |jsonb ||

...and the following data:

|insertintothing (tags)values('{"tag1": ["val1", "val2"], "tag2":
["t2val1"]}');insertintothing (tags)values('{"tag1": ["val3", "val1"],
"tag2": ["t2val1"]}');insertintothing (tags)values('{"tag1": ["val2",
"val1"], "tag2": ["t2val2"]}');|

How can I aggregate the results of a query that equates to "show me the
number of matching rows and the set of|tag1|value that have a|tag2|value
of|t2val1|?

The closes I can get is:

|#selectcount(*),json_agg(tags)fromthing wheretags->'tag2'?'t2val1';count
|json_agg
-------+--------------------------------------------------------------------------------------------------2|[{"tag1":["val1","val2"],"tag2":["t2val1"]},{"tag1":["val3","val1"],"tag2":["t2val1"]}](1row)|

...but I really want:

|count |tag1 -------+-------------------------2|["val1","val2","val3"](1row)|

cheers,

Chris

Browse pgsql-general by date

  From Date Subject
Next Message Chris Withers 2017-02-28 16:21:34 json aggregation question
Previous Message Adrian Klaver 2017-02-28 16:14:42 Re: Re: GMT FATAL: remaining connection slots are reserved for non-replication superuser connections, but I'm using pgBouncer for connection pooling