我想绘制一段时间内连接Twitter帐户的用户百分比。用户数量不断变化,连接Twitter帐户的百分比也在不断变化。
该表格包含特定于用户帐户的createDateTime
列以及tw_connectDateTime
列。
假设我对过去7天内连线趋势感兴趣。有没有办法让MSSQL计算指定范围内每一天的百分比,或者我是否需要使用多个查询自己完成?
在app逻辑中执行它看起来像(伪代码):
for day in days:
query:
select
count(userId) as totalUsers
,c.connected
,cast(c.connected as float)/count(userId) as percentage
from
Users
outer apply (
select
count(userId) as connected
from
Users
where
tw_connectDateTime <= $day
) as c
where
createDateTime <= $day
group by
c.connected
我不确定的是,如果可能的话,如何扩展它以便每天运行,以便结果包括日期作为列和我从每个运行上面的查询得到的相同值日期在范围内。
有可能吗?如果是这样,怎么样?
答案 0 :(得分:1)
实际上你可以使用你的查询加入日期,如下所示:
with cte_days as (
select @DateStart as day
union all
select dateadd(dd, 1, c.[day]) as [day]
from cte_days as c
where c.[day] < @DateEnd
)
select
d.[day],
count(u.userId) as totalUsers,
c.connected,
cast(c.connected as float)/count(u.userId) as percentage
from cte_days as d
inner join Users as u on u.createDateTime <= d.[day]
outer apply (
select
count(T.userId) as connected
from Users as T
where T.tw_connectDateTime <= d.[day]
) as c
group by d.[day], c.connected