我的理解是每個RECO在您的表中,您希望查看自己的Order1和每個具有在主要記錄之前四周內的Date值的記錄的總和。在這裏你去:
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的Date加上四周的加入小於或等於t2的Date並且t1的Date大於t2的Date。然後按t1字段對記錄進行分組,並總計t2.Order1。左外連接是對一個沒有任何先前數據的記錄進行計算。
從哪裏得到14.00的價值 – Justin 2013-03-27 08:22:37
PurchasingID 2 + 3 + 4 + 5 – Colbs 2013-03-28 15:00:35