我有下表:
Date DistrictNumber StorNumber DailyBudget
1-1-19 7100 5 0.5
1-1-19 7100 6 0.2
1-1-19 7200 21 0.7
以此类推。有超过70个区号,以及1-1 = 2018年至今的每个日期超过1000个商店号。我需要一个查询,如果“ DistrictNumber”相同的话,它将为我提供28天的“ DailyBudget”滚动总和。对于相同的标准,每年也总计。 表格示例为:
District Rolling4WTotalofDailyBudget Rolling4WLastYearDailyBudget
7100 139.5 131.6
7200 159.5 190.4
7300 147.1 151.9
7400 181.6 132.4
select bd.districtnumber,
sum(case when date between dateadd(dd,-28,dateadd(dd,-1,cast(getdate() as
date))) and dateadd(dd,-1,cast(getdate() as date)) then db.DailyBudget else 0
end) as Rolling4DailyBudget,
sum(case when date between dateadd(YY,-1,dateadd(dd,-29,cast(getdate() as
date))) and dateadd(YY,-1, dateadd(dd,-1,cast(getdate() as date))) then
db.DailyBudget else 0 end) as LYRolling4WDailyBudget
from Budget bd
group by bd.districtnumber
order by bd.districtnumber
由于某种原因,我得到了所有地区完全相同的每日预算
答案 0 :(得分:0)
我需要一个查询,如果“ DistrictNumber”相同的话,它将为我提供28天的“ DailyBudget”滚动总和
我想这就是你想要的:
select bd.districtnumber, date,
sum(sum(db.DailyBudget)) over (partition by bd.districtnumber order by date rows between 28 preceding and 1 preceding) as Rolling4WeekDailyBudget
from Budget bd
group by bd.districtnumber, date
order by bd.districtnumber, date;