2013-03-27 63 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