我有一个用户(作为guid)的大表,一些相关的值以及插入每行时的时间戳。用户可能与此表中的许多行相关联。在增长时间窗口中计数新的唯一值
guid | <other columns> | insertdate
我想统计每个月:有多少独特的新用户被插入。这很容易做手工:
select count(distinct guid)
from table
where insertdate >= '20060201' and insertdate < '20060301'
and guid not in (select guid from table where
insertdate >= '20060101' and insertdate < '20060201')
这怎么可能在SQL每个连续一个月做什么?
我想使用RANK函数关联明确每个GUID用了一个月:
select guid,
,dense_rank() over (order by datepart(YYYY, insertdate),
datepart(m, t.TransactionDateTime)) as MonthRank
from table
,然后遍历在每个等级值:
declare @no_times int
declare @counter int = 1
set @no_times = select count(distinct concat(datepart(year, t.TransactionDateTime),
datepart(month, t.TransactionDateTime))) from table
while @no_times > 0 do
(
select count(*), @counter
where guid not in (select guid from table where rank = @counter)
and rank = @int + 1
@counter += 1
@no_times -= 1
union all
)
end
我知道这个策略可能是错误的有关事情的方式。
理想情况下,我想一个结果集是这样的:
MonthRank | NoNewUsers
我会非常感兴趣,请将一个SQL向导可以在正确的方向指向我。
你可以只组了,不是吗?'datepart(mm,insertdate)'从表组中选择[count](独立的guid),datepart(mm,insertdate)作为[Month] – scsimon