2016-03-15 51 views
0

感謝您提前幫助。任何人都可以請幫我SQL查詢SQL查詢平均最近3天在表中

我日表像

> Date  | Sales_Rep_ID| Product ID | Zone | Sales 
    > 31 Jan 2015 | 001   | P01| EMEA | 10 
    > 31 Jan 2015 | 002   | P02| EMEA | 10 
    > 31 Jan 2015 | 003   | P02| EMEA | 10 
    > 30 Jan 2015 | 001   | P01| EMEA | 8 
    > 30 Jan 2015 | 002   | P02| EMEA | 7 
    > 30 Jan 2015 | 003   | P02| EMEA | 2 

,並根據日期,代表ID,產品ID

Date  | Sales_Rep_ID| Product ID | Zone | Sales | AVG_3_DAYS 
31 Jan 2015 | 001   | P01  | EMEA | 10 | 9 
31 Jan 2015 | 002   | P02  | EMEA | 10 | 8.5 
31 Jan 2015 | 003   | P02  | EMEA | 10 | 6 
30 Jan 2015 | 001   | P01  | EMEA | 8  | . 
30 Jan 2015 | 002   | P02  | EMEA | 7  | . 
30 Jan 2015 | 003   | P02  | EMEA | 2  | . 
在最後一列想要一個平均的最近n天

例如

的第1行日期爲1月31日,我們需要平均31,30,1月29日的銷售代表的001和產品ID 002

和第4行日期爲1月30日,我們需要平均爲30,29,38月爲銷售代表001和產品ID 002

+0

你的研究是什麼?你嘗試了什麼?你有我們可以修改的查詢嗎? – SWiggels

回答

1

在SQL Server中,你可以使用apply用於此目的:

select t.*, tt.avgsales 
from t outer apply 
    (select avg(sales) as avgsales 
     from t t2 
     where t2.rep_id = t.rep_id and 
      t2.product_id = t.product_id 
      t2.date <= t.date and 
      t2.date > dateadd(day, -3, t.date) 
    ) tt; 
+0

Gordon感謝您的快速回復。我試過了,但是它沒有響應模式。是否有其他方式來做到這一點。 –

+0

我會推薦't(rep_id,product_id,date)'上的索引。 –