SQL Server:从每周总计到平均每周期间

时间:2019-04-26 11:06:51

标签: sql sql-server

我有每日生产数据,我将其分为以下每周数据:

declare @rundate datetime = '2019-04-22'

select 
    convert(date, max (usedate)) as recorddate, 
    DATEDIFF(d, usedate, @rundate)/7 as weeks_ago, 
    sum(usecount) as usecountsum
from 
    usagetable
where 
    usedate <> @rundate and
    DATEDIFF(d, usedate, @rundate) >= 0 
group by 
    DATEDIFF(d, usedate, @rundate)/7
order by 
    weeks_ago asc 

任何人都可以提出一种有效的方法,从上方获取带有以下字段标题的另一张表:

recorddate  mostrecentweek      weeklyavglast4weeks weeklyavglast26weeks    weeklyavglast52weeks

谢谢

1 个答案:

答案 0 :(得分:0)

这就是我最后要去的地方:

declare @rundate datetime = '2019-04-22'

;with grp as (
select 
    convert(date, max (usedate)) as recorddate, 
    DATEDIFF(d, usedate, @rundate)/7 as weeks_ago, 
    sum(usecount) as usecountsum
from 
    usagetable
where 
    usedate <> @rundate and
    DATEDIFF(d, usedate, @rundate) >= 0 
group by 
    DATEDIFF(d, usedate, @rundate)/7
order by 
    weeks_ago asc )
select 
        usedate, 
        usecount as LastWk,  
        avg(usecount) OVER (ORDER BY usedate desc  ROWS BETWEEN 0 PRECEDING AND 3 FOLLOWING) as FourWkMA,
        avg(usecount) OVER (ORDER BY usedate desc  ROWS BETWEEN 0 PRECEDING AND 25 FOLLOWING) as TwentySixWkMA,
        avg(usecount) OVER (ORDER BY usedate desc ROWS BETWEEN 0 PRECEDING AND 51 FOLLOWING) as FiftyTwoWkMA
    from 
        grp
    order by 
        usedate desc