Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the count and list off all records according to a condition

I have the following table in postgres 14:

user  team 
1      A
10     B
113    C
12     A
1      B
113    A
12     C
1      C
113    B

What is the best way to query the count of distinct user that is in all 3 teams A, B, C and the list of all these user

The output should:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

count   list_user
2       [1, 113]

I am trying to use cte's for each one of the 3 teams but the query is running forever and is not retrieving any results then timeout.

>Solution :

We can use a double aggregation approach here:

SELECT COUNT(*) AS count,
       STRING_AGG(user::text, ',') AS list_user
FROM
(
    SELECT user
    FROM yourTable
    WHERE team IN ('A', 'B', 'C')
    GROUP BY user
    HAVING COUNT(DISTINCT team) = 3
) t;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading