计算A和B月份有多少用户

时间:2019-04-03 15:32:25

标签: sql postgresql

我想计算有usersjanuary个月的february个。我有一个具有这种结构和数据的users表:

id                         | 1
user                       | u1
month                      | january

id                         | 2
user                       | u1
month                      | february

id                         | 3
user                       | u2
month                      | january

在我的示例中,响应为1。 我尝试做SELECT COUNT(*) FROM (SELECT * FROM users WHERE users.month = 'january') s1 LEFT JOIN users s2 ON s1.user = s2.user AND s2.month = 'february';

在我的实际数据集中,此SELECT COUNT(*) FROM users WHERE users.month = 'january'返回约100,因此总体选择不可能大于此结果,但结果要高得多。

我确信答案非常简单,但是我对SQL的了解不是很熟练,所以我只是不知道应该阅读文档的哪一部分。

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select count(*)
from (select t.user
      from t
      where t.month in ('january', 'february')
      group by t.user
      having count(distinct t.month) = 2
     ) t;

如果每个用户每月最多有一行,那么join可能会有更好的性能:

select count(*)
from t tj join
     t tf
     on tj.user = tf.user and
        tj.month = 'january' and
        tf.month = 'february';

如果可以重复,则需要count(distinct user)

答案 1 :(得分:0)

具有EXISTS:

select count(distinct user)
from tablename t
where t.month in ('january', 'february')
and exists (
  select 1 from tablename where user = t.user and month > t.month
)

请参见demo