# How to filter out a group?

**URL:** https://meta.discourse.org/t/how-to-filter-out-a-group/275141
**Category:** Data & reporting
**Tags:** sql-query
**Created:** [14.Май.2018 17:49:47 UTC](https://meta.discourse.org/t/how-to-filter-out-a-group/275141 "2018-05-14T17:49:47Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![Kyle\_Selby](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/kyle_selby/32/149687_2.png) [@Kyle\_Selby](https://meta.discourse.org/u/Kyle_Selby)
#### Post date: [14.Май.2018 17:49:47 UTC](https://meta.discourse.org/t/how-to-filter-out-a-group/275141/1 "2018-05-14T17:49:47Z")

</div>

Hello all,

I am attempting to filter out a group I created named “Employees” from this [data explorer](https://meta.discourse.org/t/32566?silent=true) tab, what am I doing wrong? How do I exclude group that I have created?:

```
    SELECT 
    sum(p.score) / count(p) as "average score per post", 
    count(p.id) as post_count, 
    p.user_id
FROM posts p
JOIN users u ON u.id = p.user_id
WHERE p.created_at >= CURRENT_DATE - INTERVAL '6 month'
  AND NOT u.admin
  AND NOT u.employees
  AND u.active
GROUP by user_id, u.views
HAVING count(p.id) > 10
ORDER BY sum(p.score) / count(p) DESC
LIMIT 20

```

---

<div class="post-metadata">

### Author: ![bts](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/bts/32/184556_2.png) [@bts](https://meta.discourse.org/u/bts)
#### Post date: [14.Май.2018 19:03:24 UTC](https://meta.discourse.org/t/how-to-filter-out-a-group/275141/2 "2018-05-14T19:03:24Z")

</div>

The `users` table has `primary_group_id` (integer) so you could use that in your query if “Employees” is set as primary group for these users. Otherwise I think you’d have to do a separate join w/ the `groups` table. (Note — I don’t know the details of table structure off the top of my head but the little search thing on the right when editing a [Data Explorer](https://meta.discourse.org/t/32566?silent=true) query is super useful for this!)

---

<div class="post-metadata">

### Author: ![simon](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/simon/32/339122_2.png) [@simon](https://meta.discourse.org/u/simon)
#### Post date: [14.Май.2018 19:07:20 UTC](https://meta.discourse.org/t/how-to-filter-out-a-group/275141/3 "2018-05-14T19:07:20Z")

</div>

To get a list of users that excludes the members of a group, you could try something like this. This will exclude the members of the ‘employees’ group. It should be possible to rework your query to use this.

```plaintext
WITH group_users AS (
SELECT user_id
FROM group_users gu
JOIN groups g
ON g.id = gu.group_id
WHERE g.name = 'employees'
)

SELECT
u.id AS user_id
FROM users u
WHERE u.id NOT IN (SELECT * FROM group_users)
ORDER BY user_id

```
