[英]How to get data from the previous month result in SQL Server
I have 2 tables ms
and fr
. 我有2个表ms
和fr
。
ms
contains columns pid,month
, and totalsales
, while fr
contains pid, month
, and forecast
. ms
包含pid,month
和totalsales
列,而fr
包含pid, month
和forecast
。
In both tables, each pid
has 12 record based on month. 在两个表中,每个pid
都有基于月的12条记录。
I actually want to calculate the demand where the formula is (0.3 * totalsales) + (0.7 * previous month result of forecast)
. 我实际上想计算公式为(0.3 * totalsales) + (0.7 * previous month result of forecast)
。 The previous month result of forecast is like when the user choose pid
2 and month
2, then it will take the forecast result from month 1 as its calculation data. 上个月的预测结果就像用户选择pid
2和month
2时一样,它将以第1个月的预测结果作为其计算数据。
I tried it already but the desired result is not returned: 我已经尝试过了,但是没有返回期望的结果:
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
When I execute the code above the result is based on their each forecast
result. 当我执行上面的代码时,结果基于它们的每个forecast
结果。 For example, when I choose pid
1, month
2, then it will take the forecast
result from month
2 also. 例如,当我选择pid
1, month
2 month
,它还将采用第2 month
的forecast
结果。 meanwhile i want it to take the forecast
result from month
1 as its calculation data. 同时,我希望它以第month
的forecast
结果作为计算数据。
尝试此操作以获取上个月的SQL
SELECT Convert(datetime, DateAdd(month, -1, Convert(date, GetDate())));
Using a similar table but with a year field, using ISNULL
for no found data from previous moth, presume the previous is the month sales. 使用类似的表格,但具有年份字段,对以前的飞蛾没有找到数据使用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.