# Attempting to create Monthly Leaderboard query - head exploding

**URL:** <https://meta.discourse.org/t/attempting-to-create-monthly-leaderboard-query-head-exploding/86679>\
**Category:** Data & reporting\
**Tags:** sql-query\
**Created:** [May 3, 2018, 1:37pm UTC](https://meta.discourse.org/t/attempting-to-create-monthly-leaderboard-query-head-exploding/86679 "2018-05-03T13:37:18Z")\
**Posts on this page:** 1\
**Showing post:** 6

<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:** [July 10, 2018, 12:53am UTC](https://meta.discourse.org/t/attempting-to-create-monthly-leaderboard-query-head-exploding/86679/6 "2018-07-10T00:53:48Z")

</div>

> [@jerdog](#):
>
> trying to restrict to _only_ a specific group, and then to all _but_ a specific group (two separate queries).

I think you could create another `WITH` query to get the users who belong to a group, and then do an inner join to the in\_group table in your final query. This should exclude any records that don’t have a user\_id in the in\_group table

```plaintext
-- returns user_ids for a named group

WITH in_group AS (
SELECT
gu.user_id
FROM group_users gu
JOIN
groups g
ON g.id = gu.group_id
WHERE g.name = :group_name
)

```

If you want another query that excludes the members of a group, you could do something like this

```plaintext
not_in_group AS (
SELECT
u.id 
FROM users u
WHERE u.id NOT IN (SELECT * FROM in_group)
)

```

---

_[View the full topic](https://meta.discourse.org/t/attempting-to-create-monthly-leaderboard-query-head-exploding/86679)._
