随着时间的推移计算不同的用户

时间:2016-06-07 12:31:27

标签: sql sql-server tsql reporting-services sql-server-2012

因此数据是:

Date       | userid 
-------------------
01/01/2016 | jacby
01/01/2016 | jacby
01/01/2016 | donta
01/01/2016 | stapf
02/02/2016 | kamed
02/02/2016 | jacby
02/02/2016 | kamed
02/02/2016 | carpi
03/03/2016 | slwig
03/03/2016 | kamed

我希望能够使用SQL,TSQL或SSRS表达式生成输出,如下所示:

Date       | Unique Users
-----------------------------
01/01/2016 | 3
02/02/2016 | 5
03/03/2016 | 6

基本上是唯一身份用户的总计,参考截至该日期的唯一身份用户。即从开始那天起,我想知道自开始日期以来唯一用户的总数,正在进行中。

我可以在特定日期运行一组唯一身份用户,但这并不能说明该用户是否在前一天登录过。我确实想知道使用日期作为计数器的while循环,但实际上,我不知道从哪里开始。

我的google-fu已经过时了,我无法用正确的术语来描述我正在寻找的东西。

编辑 - 道歉 - 每个用户每天可能有多个条目。我修改了上面的源示例表。

4 个答案:

答案 0 :(得分:2)

您希望有人注册的第一次时间,然后获取此值的累积总和:

select t.date,
       sum(sum(case when seqnum = 1 then 1 else 0 end)) over (order by date) as numUniques
from (select t.*, row_number() over (partition by user order by date) as seqnum
      from t
     ) t
group by t.date
order by t.date;

您可以在子查询中放置where子句,将其限制为特定的日期集。

答案 1 :(得分:2)

这是一种方法。

if OBJECT_ID('tempdb..#Something') is not null
    drop table #Something

create table #Something
(
    MyDate date
    , UserID varchar(10)
)

insert #Something (MyDate, UserID) values
('01/01/2016', 'jacby'),
('01/01/2016', 'donta'),
('01/01/2016', 'stapf'),
('02/02/2016', 'kamed'),
('02/02/2016', 'jacby'),
('02/02/2016', 'carpi'),
('03/03/2016', 'slwig'),
('03/03/2016', 'kamed')

select distinct s.MyDate
    , 
    (
        select count(distinct UserID)
        from #Something s2
        where s2.MyDate <= s.MyDate
    ) as UniqueUsers
from #Something s

答案 2 :(得分:0)

以下查询将提供所需的输出: -

declare @table_name table
(Date date NOT NULL,
userid varchar(20) NOT NULL)

Insert into @table_name
values('01/01/2016','jacby'),
('01/01/2016','donta'),
('01/01/2016','stapf'),
('02/02/2016','kamed'),
('02/02/2016','jacby'),
('02/02/2016','carpi'),
('03/03/2016','slwig'),
('03/03/2016','kamed')



select distinct Date,
(select count(distinct userid) from @table_name TM where TM.Date<=TN.Date) [Unique Users]
from @table_name TN

输出

  Date      Unique Users
2016-01-01      3
2016-02-02      5
2016-03-03      6

答案 3 :(得分:0)

select d2.date, count(distinct d2.userid) 
  from data d1 
  join data d2 
        on d2.date <= d1.date 
 group by d2.date