6个月滚动平均值SQL

6个月滚动平均值SQL,sql,sql-server,database,tsql,Sql,Sql Server,Database,Tsql,这是我的小提琴 以上只是样本,我有3年的数据,有些行也会有空值 我需要实现: 滚动6个月平均每周销售 滚动6个月平均日销售额 这就是我正在尝试的,但不知道这种方法是否正确 select x.*, avg(avg_amount) over (partition by id order by id, trans_date rows between unbounded preceding and current row) as r

这是我的小提琴

以上只是样本,我有3年的数据,有些行也会有空值

我需要实现:

  • 滚动6个月平均每周销售
  • 滚动6个月平均日销售额
  • 这就是我正在尝试的,但不知道这种方法是否正确

    select 
        x.*,
        avg(avg_amount) over (partition by id order by id, trans_date 
                              rows between unbounded preceding and current row) as rolling_avg
    from 
        (select 
             id,
             cast(right(trans_date, 2) as int) AS Week,
             cast(left(trans_date, 4) as int) as Year, 
             trans_date, 
             sum(amount) as avg_amount
         from 
             transactiondb
         group by 
             id, trans_date) x
    

    请出示你想要的结果。我还不知道结果会是什么。我需要建立并展示给我的领导。然后我可能会有一些想法@DaleKThats一个解决问题的倒退方法。。。通常情况下,你需要手动计算出你期望的结果,这样你就知道什么时候你的查询是正确的。不清楚“滚动6个月”是什么意思,试着用你的样本数据解释一下,期望的输出也会有帮助。我想他们希望给定一组样本数据的期望输出,它不必是很多行或真实数据,只需演示您想要实现的逻辑即可
    select 
        x.*,
        avg(avg_amount) over (partition by id order by id, trans_date 
                              rows between unbounded preceding and current row) as rolling_avg
    from 
        (select 
             id,
             cast(right(trans_date, 2) as int) AS Week,
             cast(left(trans_date, 4) as int) as Year, 
             trans_date, 
             sum(amount) as avg_amount
         from 
             transactiondb
         group by 
             id, trans_date) x