在滚动的3个月内获得独特的用户数

时间:2017-06-04 16:37:05

标签: sql ms-access

所以我有一个表,其中包含一个用户名列,然后是每个用户登录我们服务时每月第一列的列。我希望得到一个独特的用户数,看看表中每个月向后滚动三个月。例如,数据如下所示:

username  Month
Bob       01/01/2017
Joe       12/01/2017
Sam       01/01/2017
Bob       01/01/2017
Joe       12/01/2017
Frank     02/01/2017
Alice     02/01/2017
John      02/01/2017
Jen       03/01/2017

我希望我的结果看起来像这样:

Month         Rolling3MonthUniqueUserCount
12/01/2017    1
01/01/2017    3
02/01/2017    6
03/01/2017    6

查询(或多个查询)必须做两件事:

  1. 确定自该日期起3个月后的第二天 表
  2. 在3个月内获取唯一身份用户数
  3. 对于我的生活,我无法弄清楚如何做到这一点,任何帮助将不胜感激。谢谢:)

    P.S。我正在使用使用T-SQL的访问。这略微限制了您可以使用的功能。

1 个答案:

答案 0 :(得分:0)

在MS-Access中,最简单的方法是相关子查询。

首先,您需要一个月份列表:

select distinct DateSerial(datecol), Month(datecol), 1)
from t;

然后,您可以使用相关子查询获取值列表:

select m.month,
       (select count(*)
        from t
        where t.datecol >= dateadd("m", -3, m.month) and
              t.datecol < m.month
       ) as rolling_count
from (select distinct DateSerial(datecol), Month(datecol), 1) as month
      from t
     ) as m;

这计算从第一个月开始的前三个完整月份。因此,1月,2月和3月的计数将在4月1日。如果您有不同的定义,可以调整查询。

这在MS Access中有效吗?

select m.month,
       (select count(*)
        from (select distinct name
              from t
              where t.datecol >= dateadd("m", -3, m.month) and
                    t.datecol < m.month
             ) as x
       ) as rolling_count
from (select distinct DateSerial(datecol), Month(datecol), 1) as month
      from t
     ) as m;

我不记得MS Access的范围规则。

相关问题