每月迄今累计的唯一用户数

时间:2019-08-08 10:22:29

标签: sql

我需要计算每月YTD的唯一用户数。我目前正在为此写逻辑。我找到了不需要唯一的值的解决方案,但是在这种情况下,事情变得更加复杂。 因此,例如,如果我有4位用户A,B,C,D,并且他们的显示方式如下:

Date          User id
============
2019/01/06    A
-------------
2019/01/25    B
-------------
2019/02/05    C
-------------
2019/02/05    A
------------
2019/03/05    C
-------------
2019/04/05    D
-------------

我的输出应该是这样的(例如,对于3月,从1月到3月底显示的唯一用户数)

MONTH   user count
=================
January  2
-----------------
February 3
-----------------
March    3
-----------------
April    4
------------------

是否有一些简单的解决方案?

非常感谢

4 个答案:

答案 0 :(得分:1)

检查一下:

DECLARE  @Table TABLE(date date , UserID varchar(250))

INSERT INTO @table values
('2019/01/06', 'A'),
('2019/01/25', 'B'),
('2019/02/05', 'C'),
('2019/02/05', 'A'),
('2019/03/05', 'C'),
('2019/04/05', 'D')


SELECT DISTINCT
   DATENAME(MONTH, Date) [Date], --This function returns a character string representing the specified datepart of the specified date.
   Count(UserID) [UserIDSum] -- it counts the amount of UserIds
FROM @Table GROUP BY Date

DATENAME的功能source

数据输出:

Date     | UserIDSum
--------------------
April    | 1
February | 2
January  | 1
March    | 1

至少这适用于MSSSQL。希望对您有帮助。

答案 1 :(得分:0)

您可以在用户出现的第一个月内对用户进行计数:

select year(min_date), month(min_date),
       count(*) as starts_in_month,
       sum(count(*)) over (order by min(min_date)
from (select user_id, min(date) as min_date
      from t
      group by user_id
     ) u
group by year(min_date), month(min_date)
order by year(min_date), month(min_date);

请注意,日期功能因数据库而异。您应该可以使用这样的构造提取年份和月份。

答案 2 :(得分:0)

请尝试以下查询,

 create table #tempt(tdate datetime, userid varchar(20));
 insert into #tempt (tdate, userid) values('2019-02-06','A');
 insert into #tempt (tdate, userid) values('2019-01-06','A');
 insert into #tempt (tdate, userid) values('2019-01-06','B');
 select * from #tempt

 select  FORMAT(tdate, 'MMMM')as Monthname, count(userid)as usercount from #tempt 
 group by tdate

答案 3 :(得分:0)

您可以尝试这个。

 declare @Table table (tdate datetime, userid varchar(20));
 insert into @Table (tdate, userid) values('2019-01-06','A');
 insert into @Table (tdate, userid) values('2019-02-06','D');
 insert into @Table (tdate, userid) values('2019-02-06','C');
 insert into @Table (tdate, userid) values('2019-02-06','A');
 insert into @Table (tdate, userid) values('2019-03-06','B');
 insert into @Table (tdate, userid) values('2019-04-06','D');
 insert into @Table (tdate, userid) values('2019-05-06','E');

; with cte as (
    select tdate, userid, year(tdate) as yr , month(tdate) as mon from @Table
 ) 
 , ct as 
 (
    select distinct c.yr, c.mon, ct.userid as cc from cte as c 
    cross join cte as ct where c.tdate>=ct.tdate
    group by c.yr, c.mon, ct.userid
  )
  select distinct yr, mon, count(cc) from ct group by yr, mon