[英]How to get data from the previous month result in SQL Server
我有2個表ms
和fr
。
ms
包含pid,month
和totalsales
列,而fr
包含pid, month
和forecast
。
在兩個表中,每個pid
都有基於月的12條記錄。
我實際上想計算公式為(0.3 * totalsales) + (0.7 * previous month result of forecast)
。 上個月的預測結果就像用戶選擇pid
2和month
2時一樣,它將以第1個月的預測結果作為其計算數據。
我已經嘗試過了,但是沒有返回期望的結果:
select
((0.3 * totalsalesamount) + (0.7 * forecastdemand)) as demand
from
Monthlysales, forecastreorder
where
Monthlysales.P_ID = forecastreorder.Productid
and Monthlysales.P_ID = 1
and forecastreorder.Month = 2
當我執行上面的代碼時,結果基於它們的每個forecast
結果。 例如,當我選擇pid
1, month
2 month
,它還將采用第2 month
的forecast
結果。 同時,我希望它以第month
的forecast
結果作為計算數據。
嘗試此操作以獲取上個月的SQL
SELECT Convert(datetime, DateAdd(month, -1, Convert(date, GetDate())));
使用類似的表格,但具有年份字段,對以前的飛蛾沒有找到數據使用ISNULL
,則假定之前的是月份銷售額。
SELECT
0.3 * ms.totalsalesamount + 0.7 * ISNULL(fr.forecastdemand, ms.totalsalesamount) as demand
FROM
ms
LEFT OUTER JOIN
fr ON ms.pid = fr.pid
AND fr.month = CASE WHEN ms.month > 1 THEN ms.month - 1 ELSE 12 END
AND fr.year = CASE WHEN ms.month > 1 THEN ms.year ELSE ms.year - 1 END
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.