2013-03-27 69 views
0

我有一张表,我想要查询前四周的订单总数。但我想用SELECT返回它(共行的前期4周Order1列 - 如果存在的话)过去4周的SQL汇总总数

PurchasingID Order1    Date   FourWeekTotal 
------------ ------------------- -------  --------------- 
1   1.00    2013-04-21 14.00 
2   2.00    2013-04-14 12.00 
3   3.00    2013-04-07 9.00 
4   4.00    2013-03-31 5.00 
5   5.00    2013-03-24 0.00 
+0

从哪里得到14.00的价值 – Justin 2013-03-27 08:22:37

+0

PurchasingID 2 + 3 + 4 + 5 – Colbs 2013-03-28 15:00:35

回答

2

我的理解是每个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。左外连接是对一个没有任何先前数据的记录进行计算。

+0

谢谢,但我甚至无法找到一个与您的查询结果一起使用的总和 - 它只返回7我的11个采购行。我需要他们全部返回与前4周订单总额(不包括当前)。我已经简化了上面的数据,如果有帮助 – Colbs 2013-03-27 05:41:46

+0

oops我的坏,我的on子句是不正确的。太困了:P现在更新。顺便说一句,根据您的样本数据,您的四周总数不包括当前记录的Order1值,这是否正确? – Moho 2013-03-27 05:57:49

+0

程序员不睡觉!这是正确的,当前Order1不包括 – Colbs 2013-03-27 06:00:00

0

尝试......

Declare @LBDate date 
SET @LBDate = DATEADD(d,-28,getdate()) 

现在写乌尔选择查询。 ..

Select * from Orders where Date between @LBDate and Getdate() 

您还可以使用所需的日期,而不是为当前日期..

+0

这将返回第一行 – Colbs 2013-03-27 05:49:05