[GENERAL] json aggregation question - Mailing list pgsql-general

From Chris Withers
Subject [GENERAL] json aggregation question
Date
Msg-id d7814043-9bf4-112b-8098-242d6386a4eb@simplistix.co.uk
Whole thread Raw
Responses Re: [GENERAL] json aggregation question  (Paul Jungwirth <pj@illuminatedcomputing.com>)
Re: [GENERAL] json aggregation question  (Yasin Sari <yasinsari81@googlemail.com>)
List pgsql-general
Hi All,

Given the following table:

# create table thing (id serial, tags jsonb);
# \d thing                        Table "public.thing"Column |  Type   |                     Modifiers                      
--------+---------+----------------------------------------------------id     | integer | not null default nextval('thing_id_seq'::regclass)tags   | jsonb   | 

...and the following data:

insert into thing (tags) values ('{"tag1": ["val1", "val2"], "tag2": ["t2val1"]}');
insert into thing (tags) values ('{"tag1": ["val3", "val1"], "tag2": ["t2val1"]}');
insert into thing (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:

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

...but I really want:

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

Chris

pgsql-general by date:

Previous
From: Chris Withers
Date:
Subject: [GENERAL] json aggregation question
Next
From: "David G. Johnston"
Date:
Subject: Re: [GENERAL] ERROR: functions in index expression must be marked IMMUTABLE