最后一个查询就是示例。Calendar 表是根据请求构建的,但是每个数据库都可以使用持久的 Calendar 表,您可以在该表上过滤日期范围。
declare @tbl table (
Month datetime,
Value decimal(10,3));
insert @tbl select
'2012-08-01', 0.345 union all select
'2012-09-01', 0.543 union all select
'2012-10-01', 0.321 union all select
'2012-11-01', 0.234 union all select
'2012-12-01', 0.234;
declare @start datetime, @end datetime;
select @start = '2012-09-29', @end ='2012-10-13';
;with Calendar(TheDate,StartOfWeek,StartOfMonth) as(
select @start, @start+1-Datepart(dw,@start), @start-Day(@start)+1
union all
select TheDate+1, TheDate+1+1-Datepart(dw,TheDate+1),
TheDate+1-Day(TheDate+1)+1
from Calendar
where TheDate < @end
)
select case when @start > v.StartOfWeek
then @start else v.StartOfWeek end RangeStart,
case when @end < v.StartOfWeek+6
then @end else v.StartOfWeek+6 end RangeEnd,
cast(avg(m.value) as decimal(10,3)) [Average]
from Calendar v
join @tbl m on v.StartOfMonth = m.Month
group by v.StartOfWeek;
输出
RANGESTART RANGEEND Average
September, 29 2012 September, 29 2012 0.543
September, 30 2012 October, 06 2012 0.353
October, 07 2012 October, 13 2012 0.321