我的理解是每个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