0

クエリで過去4週間の注文合計を取得したいテーブルがあります。しかし、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と、プライマリレコードの4週間前の日付値を持つ各レコードの合計を確認する必要があります。どうぞ:

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の日付から4週間を引いたものが、t2の日付以下であり、t1の日付がt2の日付より大きいことに基づいて参加します。次に、レコードをt1フィールドでグループ化し、t2.Order1を合計します。左外部結合は、先行データがない1つのレコードを考慮に入れるためのものです。

于 2013-03-27T05:14:04.687 に答える
0

これを試して...

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

次に、urselectクエリを記述します...

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

現在の日付の代わりに、必要な日付を使用することもできます。

于 2013-03-27T05:09:34.400 に答える