【问题标题】:Sliding Window Average For Multiple Time Periods - SQL Server多个时间段的滑动窗口平均值 - SQL Server
【发布时间】:2011-03-28 21:51:22
【问题描述】:

我有一个 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

我想看看随着时间的推移这种情况如何变化。

如何更改此查询,以便我可以输出一个带有 (Month, Avg Time to Signup for that Month) 的表?

【问题讨论】:

    标签: sql sql-server aggregate-functions


    【解决方案1】:
    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
    

    这会将最新的放在首位。

    【讨论】:

    • 如果你想要日历月,那么只需稍微修改你从数字序列中返回的日期范围。
    猜你喜欢
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2020-08-29
    • 2020-08-13
    相关资源
    最近更新 更多