我有兩個表中的數據ORDERS
和training
。 爲各種客戶提供各種培訓。我想看看這些培訓對所涉及客戶的收入有何影響。爲了實現這個目標,我想從接受培訓之日起,爲每位客戶查看過去90天和未來90天的收入。換句話說,如果客戶在2014年3月30日接受了培訓,我想看看2014年1月1日至2014年6月30日期間的收入。我想出了以下幾乎可以完成這項工作的查詢:選擇和分組過去的數據相對於某個日期
select
o.custno,
sum(ISNULL(a.revenue,0)) as Revenue,
o.Date as TrainingDate,
DATEADD(mm, DATEDIFF(mm, 0, a.created), 0) as RevenueMonth
from ORDERS a,
(select distinct custno, max(Date) as Date from Training group by custno) o
where a.custnum = o.custno
and a.created between DATEADD(day, -90, o.Date) and DATEADD(day, 90, o.Date)
group by o.custno, o.Date, DATEADD(mm, DATEDIFF(mm, 0, a.created), 0)
order by o.custno
該查詢的樣本輸出看起來是這樣的:
custno Revenue TrainingDate RevenueMonth
0000100 159.20 2014-06-02 00:00:00.000 2014-03-01 00:00:00.000
0000100 199.00 2014-06-02 00:00:00.000 2014-04-01 00:00:00.000
0000100 79.60 2014-06-02 00:00:00.000 2014-05-01 00:00:00.000
0000100 29.85 2014-06-02 00:00:00.000 2014-06-01 00:00:00.000
0000100 79.60 2014-06-02 00:00:00.000 2014-07-01 00:00:00.000
0000100 99.50 2014-06-02 00:00:00.000 2014-08-01 00:00:00.000
0000250 437.65 2013-02-26 00:00:00.000 2012-11-01 00:00:00.000
0000250 4181.65 2013-02-26 00:00:00.000 2012-12-01 00:00:00.000
0000250 4146.80 2013-02-26 00:00:00.000 2013-01-01 00:00:00.000
0000250 6211.93 2013-02-26 00:00:00.000 2013-02-01 00:00:00.000
0000250 2199.72 2013-02-26 00:00:00.000 2013-03-01 00:00:00.000
0000250 4452.65 2013-02-26 00:00:00.000 2013-04-01 00:00:00.000
所需的輸出例如:
如果提供培訓,3月15日2014年,客戶數100,我想收入數據格式如下:
CustNo Revenue TrainingDate RevenueMonth
100 <Some revenue figure> March 15 2014 Dec 15 2013 – Jan 14 2014 (Past month 1)
100 <Some revenue figure> March 15 2014 Jan 15 2014 – Feb 14 2014 (Past month 2)
100 <Some revenue figure> March 15 2014 Feb 15 2014 – Mar 14 2014 (Past month 3)
100 <Some revenue figure> March 15 2014 Mar 15 2014 – Apr 14 2014 (Future month 1)
100 <Some revenue figure> March 15 2014 Apr 15 2014 – May 14 2014 (Future month 2)
100 <Some revenue figure> March 15 2014 May 15 2014 – Jun 14 2014 (Future month 3)
這裏,RevenueMonth
列並不需要在此格式,只要它具有相對於訓練日的數據。大括號中的「過去」和「將來」月份引用僅用於解釋輸出,它們不需要出現在輸出中。
我的查詢獲取數據並按月分組數據。我希望將月份與培訓日期進行分組。例如 - 如果培訓是在3月15日進行的,我希望過去的一個月從2月15日到3月14日,我的問題不會那樣做。我相信在這個查詢中稍微調整一下就可以實現我的目標。
任何幫助查詢將不勝感激。
可視化的問題是從查詢的問題相當獨立的更新,將另行更好地問道。 – 2014-12-04 18:57:13
感謝您的建議,現在編輯該問題。 – Patthebug 2014-12-04 18:58:52
如果您正在研究培訓的效果,那麼您爲什麼會從培訓前的收入中獲得收入? – 2014-12-04 19:04:51