Среднее скользящее окно за несколько периодов времени - SQL Server - PullRequest
0 голосов
/ 29 марта 2011

У меня есть SQL-запрос, который возвращает среднее время регистрации наших пользователей, которые зарегистрировались за последние 30 дней:

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

Я хочу посмотреть, как это изменилось со временем.

Как мне изменить этот запрос, чтобы я мог выплюнуть таблицу с (Месяц, Среднее время для регистрации на этот месяц)?

1 Ответ

2 голосов
/ 29 марта 2011
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

Сначала ставится самый последний.

...