我有一张表,我希望在查询中获得前四周的订单总数。但是我想用SELECT返回它(总共行的前4周Order1列 - 如果它们存在的话)
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 :(得分:2)
我的理解是对于表中的每条记录,您希望看到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的日期减去四周小于或等于t2的日期和t1的日期大于t2的日期。然后按t1字段对记录进行分组,并将t2.Order1加起来。左外连接是为了不占任何先前数据的一条记录。
答案 1 :(得分:0)
试试这个......
Declare @LBDate date
SET @LBDate = DATEADD(d,-28,getdate())
现在写你的选择查询......
Select * from Orders where Date between @LBDate and Getdate()
您也可以使用所需的日期代替当前日期..