2

我想绘制一段时间内连接 Twitter 帐户的用户百分比。用户数量不断变化,连接 Twitter 帐户的用户百分比也在不断变化。

该表有一个用户帐户特定createDateTime的列以及一个tw_connectDateTime列。

假设我对过去 7 天的连接百分比趋势感兴趣。有没有一种方法可以让 MSSQL 计算指定范围内每天的百分比,还是我需要自己使用多个查询来计算?

在应用程序逻辑中执行它看起来像(伪代码):

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

我不确定的是,如果可能的话,如何将其扩展为每天运行,以便结果包括作为列的日期以及我从为每个日期运行上述查询获得的相同值范围。

可能吗?如果是这样,怎么做?

4

1 回答 1

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
于 2013-09-24T16:32:55.413 回答