2011-03-28 48 views
0

我有一個返回的平均時間註冊以獲得用戶誰在過去30天內簽署了一個SQL查詢:滑動窗口平均多時段 - SQL服務器

select avg(datediff(dd, acquisitiontime,createdate)) from users where 
createdate > getdate() - 30 and 
acquisitionmedium = 'cpc' and 
acquisitionsource = 'google' and 
acquisitiontime is not null 

我想看如何已經隨着時間而改變。

如何更改此查詢,以便我可以吐出一張表(月,平均時間以註冊該月)?

回答

2
select 
    DATEADD(month, -n.number, getdate()) OneMonthFromThisDate, 
    avg(datediff(dd, acquisitiontime, createdate)) AverageInThisMonth 
from users 
join master..spt_values n on n.type='P' and n.number between 1 and 24 
where createdate > DATEADD(month, -n.number, getdate()) 
    and createdate <= DATEADD(month, 1-n.number, getdate()) 
    and acquisitionmedium = 'cpc' 
    and acquisitionsource = 'google' 
    and acquisitiontime is not null 
group by n.number, DATEADD(month, -n.number, getdate()) 
order by n.number 

這使最近的第一個。

+0

如果您想要日曆月,只需稍微修改您從數字序列中返回的日期範圍。 – RichardTheKiwi 2011-03-28 22:04:13