I'd like to get all of the groups of records that have a specific value (or set of values) within a string array in PostgresSQL. For example, take the following table
+---------+------------+--------+
| user_id | date | group |
+---------+------------+--------+
| 1 | 2019-02-06 | groupA |
| 1 | 2019-02-06 | groupB |
| 1 | 2019-02-06 | groupC |
| 2 | 2019-02-06 | groupB |
| 2 | 2019-02-06 | groupC |
| 3 | 2019-02-06 | groupA |
| 3 | 2019-02-06 | groupC |
+---------+------------+--------+
I can group them with the following query:
SELECT
user_id,
date,
string_agg(group, ',') as groups
FROM t
GROUP BY
user_id,
date
which gives the following;
+---------+------------+-------------------------+
| user_id | date | groups |
+---------+------------+-------------------------+
| 1 | 2019-02-06 | {groupA,groupB,groupC} |
| 2 | 2019-02-06 | {groupB,groupC} |
| 3 | 2019-02-06 | {groupA,groupC} |
+---------+------------+-------------------------+
But I only want groups that contain groupA
. That is, here is the desired output:
+---------+------------+-------------------------+
| user_id | date | groups |
+---------+------------+-------------------------+
| 1 | 2019-02-06 | {groupA,groupB,groupC} |
| 3 | 2019-02-06 | {groupA,groupC} |
+---------+------------+-------------------------+
How do I filter out rows that don't contain groupA
?
Here's one query I've tried unsuccessfully:
SELECT
user_id,
date,
string_agg(group, ',') as groups
FROM t
GROUP BY
user_id,
date
HAVING 'groupA' IN string_agg(group, ',')