# Исключить группы из запроса «Лучшие участники»

**URL:** https://meta.discourse.org/t/exclude-groups-from-top-quality-members-query/156510
**Category:** Data & reporting
**Tags:** sql-query
**Created:** [01.Июль.2020 18:42:12 UTC](https://meta.discourse.org/t/exclude-groups-from-top-quality-members-query/156510 "2020-07-01T18:42:12Z")
**Posts on this page:** 6
**Page:** 1

<div class="post-metadata">

### Author: ![outofthebox](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/outofthebox/32/83708_2.png) [@outofthebox](https://meta.discourse.org/u/outofthebox)
#### Post date: [01.Июль.2020 18:42:12 UTC](https://meta.discourse.org/t/exclude-groups-from-top-quality-members-query/156510/1 "2020-07-01T18:42:12Z")

</div>

Привет,

Есть ли какие-либо советы по удалению определённых групп из этого запроса?

```
SELECT 
    sum(p.score) / count(p) as "средний балл на пост", 
    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 '3 month'
  AND u.active
GROUP by user_id, u.views
HAVING count(p.id) > 40
ORDER BY sum(p.score) / count(p) DESC
LIMIT 100

```

Заранее спасибо!

---

<div class="post-metadata">

### Author: ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)
#### Post date: [01.Июль.2020 20:57:32 UTC](https://meta.discourse.org/t/exclude-groups-from-top-quality-members-query/156510/2 "2020-07-01T20:57:32Z")

</div>

Я не тестировал это.

```sql
-- [параметры]
-- int_list :exclude_groups = 12, 2, 3

SELECT 
    sum(p.score) / count(p) as "средний балл на пост", 
    count(p.id) as количество_постов, 
    p.user_id
FROM posts p
JOIN users u ON u.id = p.user_id
LEFT JOIN group_users gu on u.id = gu.user_id
WHERE p.created_at >= CURRENT_DATE - INTERVAL '3 month'
  AND u.active
  AND (gu.group_id not IN (:exclude_groups))
GROUP by p.user_id, u.views
HAVING count(p.id) > 40
ORDER BY sum(p.score) / count(p) DESC
LIMIT 100

```

---

<div class="post-metadata">

### Author: ![outofthebox](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/outofthebox/32/83708_2.png) [@outofthebox](https://meta.discourse.org/u/outofthebox)
#### Post date: [02.Июль.2020 13:52:58 UTC](https://meta.discourse.org/t/exclude-groups-from-top-quality-members-query/156510/3 "2020-07-02T13:52:58Z")

</div>

Спасибо, @pfaffman. Это очень мило с вашей стороны.

Я запустил скрипт и вижу, что в результатах появляются участники исключённых групп. Конечно, они состоят во многих группах. Есть ли способ, чтобы этот скрипт полностью исключил всех участников всех групп из списка :exclude\_groups?

Благодарю за внимание.

---

<div class="post-metadata">

### Author: ![pfaffman](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pfaffman/32/120154_2.png) [@pfaffman](https://meta.discourse.org/u/pfaffman)
#### Post date: [02.Июль.2020 14:14:24 UTC](https://meta.discourse.org/t/exclude-groups-from-top-quality-members-query/156510/4 "2020-07-02T14:14:24Z")

</div>

А, точно. Оператор `not in` не сработал так, как я сначала подумал. По сути, он ничего не делает. Мне кажется, нужно сначала выполнить запрос, который находит пользователей, не состоящих ни в одной группе, а затем соединить его с остальной частью запроса.

Извините.

---

<div class="post-metadata">

### Author: ![RGJ](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/rgj/32/523185_2.png) [@RGJ](https://meta.discourse.org/u/RGJ)
#### Post date: [17.Июль.2020 07:04:02 UTC](https://meta.discourse.org/t/exclude-groups-from-top-quality-members-query/156510/5 "2020-07-17T07:04:02Z")

</div>

```sql

    -- [параметры]
    -- int_list :exclude_groups = 1,2

    SELECT 
        sum(p.score) / count(p) as "средний балл на пост", 
        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 '3 month'
      AND u.active
      AND u.id NOT IN(
        SELECT user_id FROM group_users WHERE group_id IN (:exclude_groups)
      )
    GROUP by user_id, u.views
    HAVING count(p.id) > 40
    ORDER BY sum(p.score) / count(p) DESC
    LIMIT 100

```

---

<div class="post-metadata">

### Author: ![outofthebox](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/outofthebox/32/83708_2.png) [@outofthebox](https://meta.discourse.org/u/outofthebox)
#### Post date: [20.Июль.2020 14:43:28 UTC](https://meta.discourse.org/t/exclude-groups-from-top-quality-members-query/156510/6 "2020-07-20T14:43:28Z")

</div>

@RGJ,

Ваш вклад в экосистему Discourse и ваша невероятная поддержка меня как клиента по-настоящему ценны. Я в восторге от того, что вы предоставляете столь замечательный хостинг-сервис!
