在计数函数中过滤 - Postgresql

Filtering in count function - Postgresql

我有以下查询,它提供了用户拥有的推荐数量。但是,如果被推荐的用户激活了高级计划,我只想计算推荐。这是如何实现的?

Dbfiddle here.

我正在使用 PostgreSQL 版本 14。

SELECT users.id, users.email, users.premium,
COUNT(referrals.referrer) as referred
FROM users
LEFT JOIN referrals
ON users.id = referrals.referrer
GROUP BY users.id
ORDER BY referred DESC;

您可以尝试使用FILTER子句或条件聚合函数。

SELECT users.id, users.email, users.premium,
  COUNT(referrals.referrer) FILTER(WHERE premium = true) as referred
  FROM users
  LEFT JOIN referrals
  ON users.id = referrals.referrer
  GROUP BY users.id, users.email, users.premium
  ORDER BY referred DESC;

编辑

根据你的评论,我认为你可以尝试使用子查询做聚合函数来首先找到 premium 用户,然后为 user table 做 OUTER JOIN

SELECT u.*,
       coalesce(referred,0) referred
FROM users u
LEFT JOIN(
  SELECT f.referrer,
       COUNT(f.id) FILTER(WHERE u1.premium = true) as referred
  FROM users u1
  JOIN referrals f
  ON u1.id = f.id
  GROUP BY f.referrer  
) t1
ON t1.referrer = u.id

sqlfiddle