2017-01-11 13 views
1

私は、過去30日間にどれだけの製品が販売されたのか、毎日何本が売られたのかを知りたいとしています。前と現行の間のウィンドウ関数でこれを実行しようとしましたが、問題は製品が常に毎日販売をするわけではないため、私のウィンドウ関数は30日ではなく30行を検索しているということです。30日以上経過しているウィンドウの機能

date  | prod_id | sales | wrong_answer | correct_answer 
2016-09-22 123  5  5    5 
2016-09-24 123  2  7    7 
2016-09-30 123  5  12    12 
2016-10-01 123  4  16    16 
2016-10-06 123  6  22    22 
2016-10-18 123  4  26    26 
2016-10-20 123  6  32    32 
2016-11-04 123  14  46    30 
2016-11-05 123  40  86    70 
2016-11-25 123  30  116   94 
2016-11-26 123  9  125   103 
2016-12-10 123  12  137   115 
2016-12-12 123  8  145   123 
2016-12-16 123  4  149   127 
2016-12-31 123  3  152   130 
2017-01-09 123  4  156   134 
2016-09-22 456  etc  etc   etc 

私のクエリは次のとおりです:よう

サンプル・データが見える日が当たったとき、あなたが見ることができるように

SELECT 
    date, 
    prod_id, 
    sales, 
    SUM(sales) OVER (PARTITION BY prod_id OVER BY date ASC ROWS BETWEEN 30 PRECEDING AND CURRENT ROW) as wrong_answer 
FROM prod_sales 

2016年11月4日wrong_answerはまだ戻って30行の代わりに30を探しています日々。私がしようとしていることを達成する方法はありますか?

おかげ

+0

おそらくサブクエリを使用しますか?例えばあなたのテーブルに 'PS'のようなエイリアスを与え、' mycolumn =(prod_salesから(日付、日付、PS.date)0から30の間の日付を選択してください) ' – ZLK

+0

これについては、 dba.se:[ウィンドウ関数を使用した日付範囲のローリング合計](http://dba.stackexchange.com/questions/114403/date-range-rolling-sum-using-window-functions) –

答えて

1

あなたは...

select t1.[date], t1.prod_id, t1.sales, 
(select distinct sum(sales) over(order by prod_id) 
from prod_sales as t2 where 
t2.date<= t1.date and t2.date > dateadd(day,-30,t1.date) and t2.prod_id = t1.prod_id) 
from prod_sales as t1 

30日間のウィンドウを設定している場合は、1ヶ月のウィンドウを設定している場合...

select t1.[date], t1.prod_id, t1.sales, 
(select distinct sum(sales) over(order by prod_id) 
from prod_sales as t2 where 
t2.date<= t1.date and t2.date > dateadd(month,-1,t1.date) and t2.prod_id = t1.prod_id) 
from prod_sales as t1 

注:とは少し違うの取得あなたの正解...あなたの質問を正しく得られなかったら私を修正してください。

+0

うん、最初のものは私です30日前から探しています。実際には、correct_answerの結果には31日間のウィンドウがありました。これは素晴らしいです ありがとうPramod! – onji

関連する問題