0

我有一张表,我想在查询中获取前四个星期的订单总数。但我想用 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
4

2 回答 2

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 求和。左外连接是为了说明前面没有任何数据的一条记录。

于 2013-03-27T05:14:04.687 回答
0

尝试这个...

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

现在写你的选择查询......

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

您也可以使用您需要的日期而不是当前日期..

于 2013-03-27T05:09:34.400 回答