私の理解では、テーブル内の各レコードについて、それ自体のOrder1と、プライマリレコードの4週間前の日付値を持つ各レコードの合計を確認する必要があります。どうぞ:
create table MysteryTable
(
PurchasingId int not null primary key identity(1,1),
Order1 money not null,
[Date] date not null
)
insert MysteryTable( Order1, [Date] ) values ( 1.00, '2013-04-21' )
insert MysteryTable( Order1, [Date] ) values ( 2.00, '2013-04-14' )
insert MysteryTable( Order1, [Date] ) values ( 3.00, '2013-04-07' )
insert MysteryTable( Order1, [Date] ) values ( 4.00, '2013-03-31' )
insert MysteryTable( Order1, [Date] ) values ( 5.00, '2013-03-24' )
select
t1.PurchasingId
, t1.Order1
, t1.Date
, SUM( ISNULL( t2.Order1, 0 ) ) FourWeekTotal
from
MysteryTable t1
left outer join MysteryTable t2
on DATEADD( ww, -4, t1.Date ) <= t2.Date and t1.Date > t2.Date
group by
t1.PurchasingId
, t1.Order1
, t1.Date
order by
t1.Date desc
説明:
テーブル自体を結合します。t1は返すレコードを表し、t2は集計するレコードを表します。t1の日付から4週間を引いたものが、t2の日付以下であり、t1の日付がt2の日付より大きいことに基づいて参加します。次に、レコードをt1フィールドでグループ化し、t2.Order1を合計します。左外部結合は、先行データがない1つのレコードを考慮に入れるためのものです。