您需要一个日期表,这可以通过 CTE 完成。然后,完全加入以列举您的日期......并进行除法。由于您声明数据中的日期始终是星期日,因此 7 的除数是静态的,dateadd(day,6,t.ForecastDate) 也是如此。
declare @table table (Item varchar(4), ForecastDate date, ForecastQty int)
insert into @table
values
('A123','7/30/17',140),
('A123','8/6/17',70),
('A123','8/13/17',70),
('A123','8/20/17',70),
('A123','8/27/17',70),
('A123','9/3/17',45)
declare @minDate date = (select min(ForecastDate) from @table)
declare @maxDate date = (select max(ForecastDate) from @table)
;with GetDates As
(
select @minDate as TheDate --startdate
from @table
UNION ALL
select DATEADD(day,1, TheDate) from GetDates
where TheDate <= @maxDate --maxdate
)
select distinct *
into #tempDates
from GetDates
option(maxrecursion 0)
select * from #tempDates order by TheDate
select
t.Item
,d.TheDate
,DailyFcstQty = t.ForecastQty / 7
from @table t
full outer join
#tempDates d on
d.TheDate >= t.ForecastDate
and d.TheDate <= dateadd(day,6,t.ForecastDate)
order by
t.ForecastDate
drop table #tempDates
返回
+------+------------+--------------+
| Item | TheDate | DailyFcstQty |
+------+------------+--------------+
| A123 | 2017-07-30 | 20 |
| A123 | 2017-07-31 | 20 |
| A123 | 2017-08-01 | 20 |
| A123 | 2017-08-02 | 20 |
| A123 | 2017-08-03 | 20 |
| A123 | 2017-08-04 | 20 |
| A123 | 2017-08-05 | 20 |
| A123 | 2017-08-06 | 10 |
| A123 | 2017-08-07 | 10 |
| A123 | 2017-08-08 | 10 |
| A123 | 2017-08-09 | 10 |
| A123 | 2017-08-10 | 10 |
| A123 | 2017-08-11 | 10 |
| A123 | 2017-08-12 | 10 |
| A123 | 2017-08-13 | 10 |
| A123 | 2017-08-14 | 10 |
| A123 | 2017-08-15 | 10 |
| A123 | 2017-08-16 | 10 |
| A123 | 2017-08-17 | 10 |
| A123 | 2017-08-18 | 10 |
| A123 | 2017-08-19 | 10 |
| A123 | 2017-08-20 | 10 |
| A123 | 2017-08-21 | 10 |
| A123 | 2017-08-22 | 10 |
| A123 | 2017-08-23 | 10 |
| A123 | 2017-08-24 | 10 |
| A123 | 2017-08-25 | 10 |
| A123 | 2017-08-26 | 10 |
| A123 | 2017-08-27 | 10 |
| A123 | 2017-08-28 | 10 |
| A123 | 2017-08-29 | 10 |
| A123 | 2017-08-30 | 10 |
| A123 | 2017-08-31 | 10 |
| A123 | 2017-09-01 | 10 |
| A123 | 2017-09-02 | 10 |
| A123 | 2017-09-03 | 6 |
| A123 | 2017-09-04 | 6 |
+------+------------+--------------+